<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta property="og:type" content="website">
<meta property="og:title" content="Technological Blog">
<meta property="og:url" content="http://example.com/page/4/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="Li Yudong">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/page/4/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/03/webgl/three.js%E7%B2%92%E5%AD%90%E4%B8%8E%E7%B2%BE%E7%81%B5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/10/03/webgl/three.js%E7%B2%92%E5%AD%90%E4%B8%8E%E7%B2%BE%E7%81%B5/" class="post-title-link" itemprop="url">three.js粒子</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-10-03 12:18:39" itemprop="dateCreated datePublished" datetime="2021-10-03T12:18:39+08:00">2021-10-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:22:16" itemprop="dateModified" datetime="2021-11-03T16:22:16+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webgl/" itemprop="url" rel="index"><span itemprop="name">webgl</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>使用THREE.Points可以非常容易地创建很多细小的物体，用来模拟雨滴、雪花、烟等有趣效果，你也可以将整个几何体渲染成一组粒子，并分别控制。</p>
<p>THREE.Sprite(material)构造函数可以用于手工创建粒子，传入的唯一参数为材质。与THREE.Mesh一样，THREE.Sprite对象也是对THREE.Object3D的扩展；因此可以用position属性来定位，scale属性来进行缩放，translate属性指定相对位移。</p>
<h2 id="Three-Points"><a href="#Three-Points" class="headerlink" title="Three.Points"></a>Three.Points</h2><p>利用THREE.Sprite来构建对象并移动很有效，但是当你想使用大量的该对象时，则会遇到性能问题，因为每个对象都需要THREE.js来进行管理，这里我们使用THREE.Points来做处理；这样只需要管理一个THREE.Points实例。</p>
<p>使用THREE.Points的代码如下：我们为每个粒子创建一个顶点（用THREE.Vector3表示），并将它添加到THREE.Geometry中，然后使用THREE.Geometry与THREE.PointsMaterial一起创建THREE.Points，再把云添加到场景中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createPoints</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> geom = <span class="keyword">new</span> THREE.Geometry();</span><br><span class="line">    <span class="keyword">var</span> material = <span class="keyword">new</span> THREE.PointsMaterial(&#123;</span><br><span class="line">      size: <span class="number">2</span>,</span><br><span class="line">      vertexColors: <span class="literal">true</span>,</span><br><span class="line">      color: <span class="number">0xffffff</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> x = <span class="number">-15</span>; x &lt; <span class="number">15</span>; x++) &#123;</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">var</span> y = <span class="number">-10</span>; y &lt; <span class="number">10</span>; y++) &#123;</span><br><span class="line">        <span class="keyword">var</span> particle = <span class="keyword">new</span> THREE.Vector3(x * <span class="number">4</span>, y * <span class="number">4</span>, <span class="number">0</span>);</span><br><span class="line">        geom.vertices.push(particle);</span><br><span class="line">        geom.colors.push(<span class="keyword">new</span> THREE.Color(<span class="built_in">Math</span>.random() * <span class="number">0xffffff</span>));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> cloud = <span class="keyword">new</span> THREE.Points(geom, material);</span><br><span class="line">    scene.add(cloud);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>THREE.Points的构造函数接收两个属性，几何体和材质；材质用于给粒子着色与添加纹理，而几何体则用于指定单个粒子的位置。每个顶点和每个用来定义几何体的点，将会以粒子的形态展示出来。如果我们基于THREE.BoxGeometry对象来创建THREE.Points对象，将会得到8个粒子，方块的每个角上各一个。</p>
<p>但一般情况下，我们都会选择使用THREE.PointsMaterial来样式化粒子。如下代码，我们创建了一个THREE.Points对象，并添加了15000个粒子，且所有粒子均由THREE.PointsMaterial样式化。</p>
<p>代码逻辑如下：1、创建一个THREE.Geometry对象；2、把用THREE.Vector3对象表示的粒子添加至几何体。3、定义颜色数组geom.colors。4、创建THREE.PointsMaterial。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createParticles</span>(<span class="params">size, transparent, opacity, vertexColors, sizeAttenuation, colorValue, vertexColorValue</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> geom = <span class="keyword">new</span> THREE.Geometry();</span><br><span class="line">    <span class="keyword">var</span> material = <span class="keyword">new</span> THREE.PointsMaterial(&#123;</span><br><span class="line">      size: size,</span><br><span class="line">      transparent: transparent,</span><br><span class="line">      opacity: opacity,</span><br><span class="line">      vertexColors: vertexColors,</span><br><span class="line"></span><br><span class="line">      sizeAttenuation: sizeAttenuation,</span><br><span class="line">      color: <span class="keyword">new</span> THREE.Color(colorValue)</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> range = <span class="number">500</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">15000</span>; i++) &#123;</span><br><span class="line">      <span class="keyword">var</span> particle = <span class="keyword">new</span> THREE.Vector3(<span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>, <span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>,</span><br><span class="line">        <span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>);</span><br><span class="line">      geom.vertices.push(particle);</span><br><span class="line">      <span class="keyword">var</span> color = <span class="keyword">new</span> THREE.Color(vertexColorValue);</span><br><span class="line">      <span class="keyword">var</span> asHSL = &#123;&#125;;</span><br><span class="line">      color.getHSL(asHSL);</span><br><span class="line">      color.setHSL(asHSL.h, asHSL.s, asHSL.l * <span class="built_in">Math</span>.random());</span><br><span class="line">      geom.colors.push(color);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    cloud = <span class="keyword">new</span> THREE.Points(geom, material);</span><br><span class="line">    cloud.name = <span class="string">"particles"</span>;</span><br><span class="line">    scene.add(cloud);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>到目前为止，其实我们只是将粒子渲染成为小方块，这时粒子特效的默认行为，而其实还有其他更多的粒子效果实现方式，具体方式如下：</p>
<h2 id="HTML5画布"><a href="#HTML5画布" class="headerlink" title="HTML5画布"></a>HTML5画布</h2><p>THREE.js提供了三种使用HTML5画布来样式化粒子的方法。</p>
<h3 id="THREE-CanvasRenderer"><a href="#THREE-CanvasRenderer" class="headerlink" title="THREE.CanvasRenderer"></a>THREE.CanvasRenderer</h3><p>通过THREE.SpriteCanvasMaterial，可以将HTML5画布的输出结果作为粒子的纹理，该纹理仅有在使用THREE.CanvasRenderer时，才能够生效。具体的代码如下：由于我们使用的是THREE.CanvasRenderer，因此不使用THREE.Points，而是直接创建THREE.Sprite对象，且我们使用program属性来定义THREE.SpriteCanvasMaterial，program属性指向getTexture函数，该函数定义了粒子的外观。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSprites</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> material = <span class="keyword">new</span> THREE.SpriteCanvasMaterial(&#123;</span><br><span class="line">      program: getTexture</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    material.rotation = <span class="built_in">Math</span>.PI;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> range = <span class="number">500</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">1500</span>; i++) &#123;</span><br><span class="line">      <span class="keyword">var</span> sprite = <span class="keyword">new</span> THREE.Sprite(material);</span><br><span class="line">      sprite.position.set(<span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>, <span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>, <span class="built_in">Math</span>.random() *</span><br><span class="line">        range - range / <span class="number">2</span>);</span><br><span class="line">      sprite.scale.set(<span class="number">0.1</span>, <span class="number">0.1</span>, <span class="number">0.1</span>);</span><br><span class="line">      scene.add(sprite);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> getTexture = <span class="function"><span class="keyword">function</span> (<span class="params">ctx</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// the body</span></span><br><span class="line">    ctx.translate(<span class="number">-81</span>, <span class="number">-84</span>);</span><br><span class="line">    ctx.fillStyle = <span class="string">"orange"</span>;</span><br><span class="line">    ctx.beginPath();</span><br><span class="line">    ctx.moveTo(<span class="number">83</span>, <span class="number">116</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">83</span>, <span class="number">102</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">83</span>, <span class="number">94</span>, <span class="number">89</span>, <span class="number">88</span>, <span class="number">97</span>, <span class="number">88</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">105</span>, <span class="number">88</span>, <span class="number">111</span>, <span class="number">94</span>, <span class="number">111</span>, <span class="number">102</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">111</span>, <span class="number">116</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">106.333</span>, <span class="number">111.333</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">101.666</span>, <span class="number">116</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">97</span>, <span class="number">111.333</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">92.333</span>, <span class="number">116</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">87.666</span>, <span class="number">111.333</span>);</span><br><span class="line">    ctx.lineTo(<span class="number">83</span>, <span class="number">116</span>);</span><br><span class="line">    ctx.fill();</span><br><span class="line">    <span class="comment">// the eyes</span></span><br><span class="line">    ctx.fillStyle = <span class="string">"white"</span>;</span><br><span class="line">    ctx.beginPath();</span><br><span class="line">    ctx.moveTo(<span class="number">91</span>, <span class="number">96</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">88</span>, <span class="number">96</span>, <span class="number">87</span>, <span class="number">99</span>, <span class="number">87</span>, <span class="number">101</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">87</span>, <span class="number">103</span>, <span class="number">88</span>, <span class="number">106</span>, <span class="number">91</span>, <span class="number">106</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">94</span>, <span class="number">106</span>, <span class="number">95</span>, <span class="number">103</span>, <span class="number">95</span>, <span class="number">101</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">95</span>, <span class="number">99</span>, <span class="number">94</span>, <span class="number">96</span>, <span class="number">91</span>, <span class="number">96</span>);</span><br><span class="line">    ctx.moveTo(<span class="number">103</span>, <span class="number">96</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">100</span>, <span class="number">96</span>, <span class="number">99</span>, <span class="number">99</span>, <span class="number">99</span>, <span class="number">101</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">99</span>, <span class="number">103</span>, <span class="number">100</span>, <span class="number">106</span>, <span class="number">103</span>, <span class="number">106</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">106</span>, <span class="number">106</span>, <span class="number">107</span>, <span class="number">103</span>, <span class="number">107</span>, <span class="number">101</span>);</span><br><span class="line">    ctx.bezierCurveTo(<span class="number">107</span>, <span class="number">99</span>, <span class="number">106</span>, <span class="number">96</span>, <span class="number">103</span>, <span class="number">96</span>);</span><br><span class="line">    ctx.fill();</span><br><span class="line">    <span class="comment">// the pupils</span></span><br><span class="line">    ctx.fillStyle = <span class="string">"blue"</span>;</span><br><span class="line">    ctx.beginPath();</span><br><span class="line">    ctx.arc(<span class="number">101</span>, <span class="number">102</span>, <span class="number">2</span>, <span class="number">0</span>, <span class="built_in">Math</span>.PI * <span class="number">2</span>, <span class="literal">true</span>);</span><br><span class="line">    ctx.fill();</span><br><span class="line">    ctx.beginPath();</span><br><span class="line">    ctx.arc(<span class="number">89</span>, <span class="number">102</span>, <span class="number">2</span>, <span class="number">0</span>, <span class="built_in">Math</span>.PI * <span class="number">2</span>, <span class="literal">true</span>);</span><br><span class="line">    ctx.fill();</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>

<h3 id="WebGLRenderer"><a href="#WebGLRenderer" class="headerlink" title="WebGLRenderer"></a>WebGLRenderer</h3><p>如果我们想要在WebGLRenderer中使用HTML画布，可以才采取两种不同方法。1、使用THREE.PointsMaterial并创建THREE.Points对象；2、使用THREE.Sprite和THREE.SpriteMaterial的map属性。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createGhostTexture</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">'canvas'</span>);</span><br><span class="line">    canvas.width = <span class="number">32</span>;</span><br><span class="line">    canvas.height = <span class="number">32</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">'2d'</span>);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//第一个函数crreateGhostTexture中，我们基于H5的画布元素创建了一个THREE.Texture对象。</span></span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createPoints</span>(<span class="params">size, transparent, opacity, sizeAttenuation, color</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> geom = <span class="keyword">new</span> THREE.Geometry();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> material = <span class="keyword">new</span> THREE.PointsMaterial(&#123;</span><br><span class="line">      size: size,</span><br><span class="line">      transparent: transparent,</span><br><span class="line">      opacity: opacity,</span><br><span class="line">      map: createGhostTexture(),</span><br><span class="line">      sizeAttenuation: sizeAttenuation,</span><br><span class="line">      color: color</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> range = <span class="number">500</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5000</span>; i++) &#123;</span><br><span class="line">      <span class="keyword">var</span> particle = <span class="keyword">new</span> THREE.Vector3(<span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>, <span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>,</span><br><span class="line">        <span class="built_in">Math</span>.random() * range - range / <span class="number">2</span>);</span><br><span class="line">      geom.vertices.push(particle);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    cloud = <span class="keyword">new</span> THREE.Points(geom, material);</span><br><span class="line">    cloud.name = <span class="string">'points'</span>;</span><br><span class="line">    scene.add(cloud);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//第二个函数中，我们将纹理赋给THREE.PointsMaterial的map属性。</span></span><br><span class="line">  <span class="comment">//上述函数的调用结果是：在createGhostTexture方法中绘制到画布上恶的所有内容都会用于THREE.points的粒子。</span></span><br></pre></td></tr></table></figure>

<h2 id="纹理样式化粒子"><a href="#纹理样式化粒子" class="headerlink" title="纹理样式化粒子"></a>纹理样式化粒子</h2><p>使用图像样式化粒子其实还有更直接的方法，可以使用THREE.TextureLoader().load()函数将图像加载为THREE.Texture对象，然后就可以将THREE.Texture分配给材质的map属性。</p>
<h2 id="使用精灵贴图"><a href="#使用精灵贴图" class="headerlink" title="使用精灵贴图"></a>使用精灵贴图</h2><h2 id="从高级几何体创建Points"><a href="#从高级几何体创建Points" class="headerlink" title="从高级几何体创建Points"></a>从高级几何体创建Points</h2>
      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/30/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E6%9F%A5%E6%89%BE%E4%B8%8E%E6%8E%92%E5%BA%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/30/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E6%9F%A5%E6%89%BE%E4%B8%8E%E6%8E%92%E5%BA%8F/" class="post-title-link" itemprop="url">查找与排序</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-30 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-30T12:18:39+08:00">2021-09-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-19 17:18:41" itemprop="dateModified" datetime="2021-10-19T17:18:41+08:00">2021-10-19</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">设计模式</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="查找"><a href="#查找" class="headerlink" title="查找"></a>查找</h1><p>查找表：是由同一类型的数据元素（或记录）构成的集合。关键字Key是数据元素中某个数据项的值，又称为键值，用它可以标识一个数据元素。若此关键字可以唯一地标识一个记录，则称此关键字为主关键字。对于哪些可以识别多个数据元素的关键字，我们称为次关键字。</p>
<p>查找：就是根据给定的某个值，在查找表中确定一个其关键字等于给定值的数据元素。</p>
<p>查找表的操作方式大致分为两种，静态查找表与动态查找表。静态查找表又称：只作查找操作的查找表，1、查询某个特定的数据元素是否在查找表中；2、检索某个特定的数据元素和各种属性。</p>
<p>动态查找表：在查找过程中同时插入查找表中不存在的数据元素，或者从查找表中删除已经存在的某个数据元素。</p>
<h2 id="顺序表查找"><a href="#顺序表查找" class="headerlink" title="顺序表查找"></a>顺序表查找</h2><p>顺序表查找是最基本的查找，又称为遍历查找，时间复杂度为O(n)。</p>
<h2 id="有序表查找"><a href="#有序表查找" class="headerlink" title="有序表查找"></a>有序表查找</h2><h3 id="折半查找"><a href="#折半查找" class="headerlink" title="折半查找"></a>折半查找</h3><p>折半查找又称二分查找，其本质是取中间值作为比较对象，能够通过数值间的关系，判断要查找的值究竟在中间值的左侧还是右侧，其实也不一定需要排序，只需要能知道在左侧还是右侧即可。折半查找的题目一般不难，重要的是要有这种思维，折半也不是必须要排序的。</p>
<p>折半算法的时间复杂度是O(logn)，它明显远远好于顺序查找的时间复杂度。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。</span></span><br><span class="line"><span class="comment">如果数组中不存在目标值 target，返回 [-1, -1]。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number[]&#125;</span> <span class="variable">nums</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> <span class="variable">target</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number[]&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> searchRange = <span class="function"><span class="keyword">function</span> (<span class="params">nums, target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> mid, midL, midR;</span><br><span class="line">    <span class="comment">// 搜索右边界</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">searchR</span>(<span class="params">left, right, target</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (left &lt;= right) &#123;</span><br><span class="line">            mid = (left + right) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">if</span> (nums[mid] &lt;= target) left = mid + <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">else</span> right = mid - <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> right</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 在区间[0, nums.length - 1]搜索target的右边界midR</span></span><br><span class="line">    midR = searchR(<span class="number">0</span>, nums.length - <span class="number">1</span>, target)</span><br><span class="line">    <span class="comment">// midR &lt; 0说明超过边界；nums[midR] !== target说明无此元素；</span></span><br><span class="line">    <span class="keyword">if</span> (midR &lt; <span class="number">0</span> || nums[midR] !== target) <span class="keyword">return</span> [<span class="number">-1</span>, <span class="number">-1</span>]</span><br><span class="line">    <span class="comment">// 在区间[0, midR - 1]搜索target - 1的右边界midL</span></span><br><span class="line">    midL = searchR(<span class="number">0</span>, midR - <span class="number">1</span>, target - <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> [midL + <span class="number">1</span>, midR]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="插值查找"><a href="#插值查找" class="headerlink" title="插值查找"></a>插值查找</h3><p>查找时，为什么一定要折半，而不是折四分之一。我们可以根据范围大小，决定一下折半还是其他的遍历方式。</p>
<p>插值查找：是根据查找的关键字key与查找表中最大最小记录的关键字比较后的查找方法，其核心在于插值公式：(key - a[low])/(a[high] - a[low])。</p>
<p>mid = low + (high - low) * (key - a[low])/(a[high] - a[low])。</p>
<h3 id="斐波那契查找"><a href="#斐波那契查找" class="headerlink" title="斐波那契查找"></a>斐波那契查找</h3><p>本质上也是分隔点的不同。mid = low + F[K - 1] - 1。</p>
<h2 id="线性索引查找"><a href="#线性索引查找" class="headerlink" title="线性索引查找"></a>线性索引查找</h2><p>之间高效的查找方法都是基于数据有序的基础上的，然后事实上一些数据集会增长地特别快，例如微博等网站的评论，这些数据通常都是用先后顺序来进行存储的。对于这样的查找表，我们如何能够快速查找到需要的数据：索引。</p>
<p>索引就是把一个关键字与它对应的记录相关联的过程，一个索引由若干个索引项构成，每个索引项至少应包括关键字和其对应的记录在存储器中的位置等信息。</p>
<p>索引按照结构可分为线性索引、树形索引和多级索引。线性索引就是将索引项集合组织为线性结构，也称为索引表。</p>
<h3 id="稠密索引"><a href="#稠密索引" class="headerlink" title="稠密索引"></a>稠密索引</h3><p>稠密索引：在线性索引中，将数据集中的每个记录对应一个索引项。索引项是关键码有序的，这样就可以用有序表查找的方法。</p>
<h3 id="分块索引"><a href="#分块索引" class="headerlink" title="分块索引"></a>分块索引</h3><p>稠密索引因为索引项与数据集的记录个数相同，所以空间代价很大；为减少索引项的个数，我们可以对数据集进行分块，使其分块有序，然后再对每一块简历一个索引项，从而减少索引项的个数。</p>
<p>分块有序，是把数据集的记录分成了若干块，并且这些块要满足两个条件：1、块内无序；2、块间有序。</p>
<h3 id="倒排索引"><a href="#倒排索引" class="headerlink" title="倒排索引"></a>倒排索引</h3><p>索引表的通用结构：次关键码、记录号表。其中，记录号表存储具有相同次关键字的所有记录的记录号，这样的索引方法就是倒排索引。</p>
<p>倒排索引的优点显然是查找记录非常块，基本等于生成索引表后，查找时不用去读取记录，但它的缺点是该记录号不定长。</p>
<h2 id="二叉排序树"><a href="#二叉排序树" class="headerlink" title="二叉排序树"></a>二叉排序树</h2><p>二叉排序树又称二叉查找树，在堆排序时十分常见。这里我们主要还是写一下堆排序的代码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*堆排序 */</span></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">      *<span class="doctag">@Description</span>:堆排序</span></span><br><span class="line"><span class="comment">      *<span class="doctag">@param </span>arr </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">headSort</span>(<span class="params">arr</span>)</span>&#123;</span><br><span class="line">        buildHeap(arr);<span class="comment">//构建堆</span></span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=len<span class="number">-1</span>;i&gt;<span class="number">0</span>;i--)&#123;</span><br><span class="line">            swap(arr,<span class="number">0</span>,i);<span class="comment">//交换堆的第一个元素和最后一个元素</span></span><br><span class="line">            heapify(arr,i);<span class="comment">//调整堆</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> arr;</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:创建堆</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param <span class="variable">arr</span></span></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">buildHeap</span>(<span class="params">arr</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">if</span>(len == <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="built_in">Math</span>.floor(len/<span class="number">2</span>) - <span class="number">1</span>;i&gt;<span class="number">0</span>;i--)&#123;</span><br><span class="line">            heapify(arr,i);<span class="comment">//在构建堆时，就需要一个个地调整堆</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:调整堆</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param </span>arr 调整数组</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param </span>i 跟</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">heapify</span>(<span class="params">arr,i</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> left = <span class="number">2</span>*i+<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">var</span> right = <span class="number">2</span>*i+<span class="number">2</span>;</span><br><span class="line">        <span class="keyword">var</span> largest = i;</span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">if</span>(left &lt;len &amp;&amp; arr[left]&gt;arr[largest])&#123;<span class="comment">//先判断左节点还否超出</span></span><br><span class="line">            largest=left;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(right &lt;len &amp;&amp; arr[right]&gt;largest)&#123;<span class="comment">//右节点是否超出 找出最大的子节点</span></span><br><span class="line">            largest=right;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(largest != i)&#123;</span><br><span class="line">            swap(arr,i,largest);<span class="comment">//交换 largrst为i，这里交换的是两者序数对应的值</span></span><br><span class="line">            heapify(arr,largest);</span><br><span class="line"><span class="comment">//递归调整，如果左侧为largest，那么将左侧节点提上去，会影响左侧子树的原本正确排序，因此。递归调整左侧；递归调用的参数是，为最大的那一个</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:交换</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param <span class="variable">arr</span></span></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">swap</span>(<span class="params">arr,i,j</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> temp=arr[i];</span><br><span class="line">        arr[i] = arr[j];</span><br><span class="line">        arr[j] = temp;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="平衡二叉树"><a href="#平衡二叉树" class="headerlink" title="平衡二叉树"></a>平衡二叉树</h2><p>平衡二叉树是一种二叉排序树，其中每一个节点的左子树和右子树的高度查至多等于1。</p>
<p>我们可以利用递归的方式，来判断一个二叉树是否是平衡二叉树。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"> * function TreeNode(val, left, right) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = (val===undefined ? 0 : val)</span></span><br><span class="line"><span class="comment"> *     this.left = (left===undefined ? null : left)</span></span><br><span class="line"><span class="comment"> *     this.right = (right===undefined ? null : right)</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;TreeNode&#125;</span> <span class="variable">root</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;boolean&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> isBalanced = <span class="function"><span class="keyword">function</span> (<span class="params">root</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> balanced(root) !== <span class="number">-1</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> balanced = <span class="function"><span class="keyword">function</span> (<span class="params">node</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!node) <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">  <span class="keyword">const</span> left = balanced(node.left)</span><br><span class="line">  <span class="keyword">const</span> right = balanced(node.right)</span><br><span class="line">  <span class="keyword">if</span> (left === <span class="number">-1</span> || right === <span class="number">-1</span> || <span class="built_in">Math</span>.abs(left - right) &gt; <span class="number">1</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="number">-1</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.max(left, right) + <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样，我们也可以用下面的方式，给出一个二叉搜索树，将其变为平衡二叉树。</p>
<p>下面的第一个做法其实有些取巧了。重新获取了整个树的结点值，再对其排序并重新构建二叉树，时间复杂度会比较高，更好的方法和思路应该是后面那一个。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> balanceBST = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 获取节点值。bst中序遍历返回升序数组。</span></span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    <span class="keyword">let</span> fn = <span class="function">(<span class="params">node</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(!node)<span class="keyword">return</span>;</span><br><span class="line">        fn(node.left);</span><br><span class="line">        arr.push(node.val);</span><br><span class="line">        fn(node.right);</span><br><span class="line">    &#125;;</span><br><span class="line">    fn(root);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 重建平衡bst</span></span><br><span class="line">    <span class="keyword">let</span> mid = ~~(arr.length / <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">let</span> h = <span class="keyword">new</span> TreeNode(arr[mid]);</span><br><span class="line">    <span class="keyword">let</span> buildTree = <span class="function">(<span class="params">node, arr, mid</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(!arr.length || arr.length === <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(arr.length === <span class="number">2</span>)&#123; <span class="comment">// 跟mid的划分有关，有两个数，mid是右侧那个</span></span><br><span class="line">            node.left = <span class="keyword">new</span> TreeNode(arr[<span class="number">0</span>]);</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 左树</span></span><br><span class="line">        node.left = <span class="keyword">new</span> TreeNode(arr[~~(mid / <span class="number">2</span>)]);</span><br><span class="line">        buildTree(node.left, arr.slice(<span class="number">0</span>, mid), ~~(mid / <span class="number">2</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 右树</span></span><br><span class="line">        <span class="keyword">let</span> a = arr.slice(mid+<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">let</span> mi = ~~(a.length / <span class="number">2</span>);</span><br><span class="line">        node.right = <span class="keyword">new</span> TreeNode(a[mi]);</span><br><span class="line">        buildTree(node.right, a, mi)</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">// 参数解释：给定一个数组，已经锁定了head和head的index</span></span><br><span class="line">    buildTree(h, arr, mid);</span><br><span class="line">    <span class="keyword">return</span> h;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>解题思路：每一棵二叉树都要判断平衡因子，如果不平衡就调整它；<br>如果左边的平衡因子大就向右转移<br>如果右边的平衡因子大就向右转移<br>然后，再判断二叉树的左右子树的平衡因子是否符合平衡二叉树的性质</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"> * function TreeNode(val) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = val;</span></span><br><span class="line"><span class="comment"> *     this.left = this.right = null;</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;TreeNode&#125;</span> <span class="variable">root</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;TreeNode&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> balanceBST = <span class="function"><span class="keyword">function</span> (<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="literal">null</span>) <span class="keyword">return</span> root;</span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> leftHeight = get_num(root.left);</span><br><span class="line">        <span class="keyword">let</span> rightHeight = get_num(root.right);</span><br><span class="line">        <span class="keyword">let</span> sub = leftHeight - rightHeight;</span><br><span class="line">        <span class="keyword">if</span> (sub &gt;= <span class="number">-1</span> &amp;&amp; sub &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (sub &lt; <span class="number">-1</span>) &#123;</span><br><span class="line">            root = turn_left(root)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            root = turn_right(root);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    root.left = balanceBST(root.left);</span><br><span class="line">    root.right = balanceBST(root.right);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">turn_left</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> currNode = root.right;</span><br><span class="line">    <span class="comment">// 找到root结点的最左边结点</span></span><br><span class="line">    find_min(currNode).left = root;</span><br><span class="line">    root.right = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">return</span> currNode;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">turn_right</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> currNode = root.left;</span><br><span class="line">    <span class="comment">// 找到root结点的最右边结点</span></span><br><span class="line">    find_max(currNode).right = root;</span><br><span class="line">    root.left = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">return</span> currNode;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">find_min</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root.left == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> root;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line">    <span class="keyword">while</span> (node.left != <span class="literal">null</span>) &#123;</span><br><span class="line">        node = node.left;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> node;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">find_max</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> node = root.right;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> root;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (node.right != <span class="literal">null</span>) &#123;</span><br><span class="line">        node = node.right;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> node;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">get_num</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!root) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> get_num(root.left) + <span class="number">1</span> + get_num(root.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="多路查找树（B树）"><a href="#多路查找树（B树）" class="headerlink" title="多路查找树（B树）"></a>多路查找树（B树）</h2><p>多路查找树：B树，其每一个结点的海子叔可以多余两个，且每一个结点处可以存储多个元素。</p>
<p>2-3树就是这样的一个查找树，其中的每一个结点都具有两个孩子或者3个孩子。一个2结点包含一个元素和两个孩子；一个3结点包含一大一小两个元素和三个孩子。</p>
<h3 id="B树"><a href="#B树" class="headerlink" title="B树"></a>B树</h3><p>B树是一种平衡的多路查找树，结点最大的孩子数目称为B树的阶。一个m阶的B树具有以下的属性：</p>
<p>1、如果一个结点不是叶结点，则其至少有两个子树；</p>
<p>2、每一个非根的分支节点都有k-1个元素和k个孩子，其中m/2 &lt;= k &lt;= m。每一个叶子节点都有k-1个元素。</p>
<p>3、所有叶子节点都位于同一层次。</p>
<p>4、所有分支节点包含以下信息数据(n,A0,K1,A1,A2,…,Kn,An)，其中Ki为关键字，且Ki&lt;Ki+1；Ai为指向子树根节点的指针，且指针Ai-1所指子树中所有结点的关键字均小于Ki，An所指子树中所有结点的关键字均大于Kn，n为关键字的个数。</p>
<p>在B树上查找的过程：是一个顺时针查找结点和在结点中查找关键字的交叉过程。</p>
<h3 id="B-树"><a href="#B-树" class="headerlink" title="B+树"></a>B+树</h3><p>B+树是应文件系统所需而出的一种B树的变形。在B+树中，出现在分支结点中的元素会被当做它们在该分支结点位置的中序后继者中再次列出。另外，每一个叶子结点都会保存一个指向后一叶子结点的指针。</p>
<h2 id="散列表"><a href="#散列表" class="headerlink" title="散列表"></a>散列表</h2><p>散列技术：是在记录的存储位置和它的关键字之间建立一个确定的对应关系f，使得每个关键字key对应的一个存储位置f。 这里我们把对应关系称为散列函数，又称hash函数。</p>
<h1 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h1><h2 id="排序的分类"><a href="#排序的分类" class="headerlink" title="排序的分类"></a>排序的分类</h2><p>稳定性：假设Ki=Kj，且在排序前的序列中Ri领先于Rj。如果排序后Ri仍领先于Rj，则称所用的排序方法是稳定的；反之，若可能使得排序后的序列中Rj领先于Ri，则称所用的排序方法是不稳定的。</p>
<p>内排序与外排序：</p>
<p>内排序：在整个排序过程中，待排序的所有记录全部被放置在内存中。外排序是由于排序的记录个数过多，不能同时放置在内存，整个排序过程需要在内外村之间多次交换数据才能进行。</p>
<h2 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h2><p>冒泡排序是一种交换排序，它基本思想是：两两比较相邻记录的关键字，如果反序列则交换，直到没有反序的记录为止。</p>
<p>其时间复杂度为O(n * n)。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*冒泡排序</span></span><br><span class="line"><span class="comment">1.比较相邻的元素。如果第一个比第二个大，就交换它们两个</span></span><br><span class="line"><span class="comment">2.对每一对相邻元素作同样的工作，从开始第一对到结尾的最后一对，这样在最后的元素应该会是最大的数</span></span><br><span class="line"><span class="comment">3.除去最右的元素，我们对剩余的元素做同样（1、2）的工作，如此重复下去，直到排序完成。</span></span><br><span class="line"><span class="comment">这里我们把排序的方法封装到Array的原型链对象上，这样随便一个数组就可以直接调用了 */</span></span><br><span class="line"><span class="built_in">Array</span>.prototype.bubbleSort = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> len = <span class="keyword">this</span>.length</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> j=<span class="number">1</span>; j&lt;len; j++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i=<span class="number">0</span>; i&lt;len-j; i++) &#123;<span class="comment">//i &lt; len - j;用于确保每次循环均排好一个数，不再考虑</span></span><br><span class="line">            <span class="comment">// 开始比较，如果第一个数大于第二个数就进行交换，这样大的就到后面去了</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>[i] &gt; <span class="keyword">this</span>[i+<span class="number">1</span>]) &#123;</span><br><span class="line">                <span class="keyword">let</span> tempnum = <span class="keyword">this</span>[i+<span class="number">1</span>]</span><br><span class="line">                <span class="keyword">this</span>[i+<span class="number">1</span>] = <span class="keyword">this</span>[i]</span><br><span class="line">                <span class="keyword">this</span>[i] = tempnum</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">2</span>,<span class="number">9</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">3</span>,<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"原来："</span>, arr.toString())</span><br><span class="line"><span class="comment">// 原来： 2,9,5,7,1,1,6,3,3,4</span></span><br><span class="line">arr.bubbleSort()</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"排序后："</span>, arr.toString())</span><br><span class="line"><span class="comment">// 排序后： 1,1,2,3,3,4,5,6,7,9</span></span><br></pre></td></tr></table></figure>

<h2 id="希尔排序"><a href="#希尔排序" class="headerlink" title="希尔排序"></a>希尔排序</h2><p>希尔排序并不是一种稳定的排序方式，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*希尔排序</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">shellSort</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> len = arr.length;</span><br><span class="line">    <span class="comment">// gap 即为增量</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> gap = <span class="built_in">Math</span>.floor(len / <span class="number">2</span>); gap &gt; <span class="number">0</span>; gap = <span class="built_in">Math</span>.floor(gap / <span class="number">2</span>)) &#123;</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = gap; i &lt; len; i++) &#123;<span class="comment">//对于后面的，都要进行插入排序，组内进行插入排序</span></span><br><span class="line">        <span class="keyword">let</span> j = i;</span><br><span class="line">        <span class="keyword">let</span> current = arr[i];<span class="comment">//对于每个新加进来的数，需要进行直接插入排序，即对其一个个地进行往前有序区试探，从而排序</span></span><br><span class="line">        <span class="keyword">while</span>(j - gap &gt;= <span class="number">0</span> &amp;&amp; current &lt; arr[j - gap]) &#123;<span class="comment">//没有实际上用数组来保存而实现分组，而实用gap来表示间隔，这样就能自动分开</span></span><br><span class="line">          arr[j] = arr[j - gap];</span><br><span class="line">          j = j - gap;</span><br><span class="line">        &#125;</span><br><span class="line">        arr[j] = current;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">var</span> arr = [<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">1</span>,<span class="number">4</span>,<span class="number">56</span>,<span class="number">12</span>,<span class="number">78</span>,<span class="number">25</span>,<span class="number">0</span>,<span class="number">9</span>,<span class="number">8</span>,<span class="number">42</span>,<span class="number">37</span>];</span><br><span class="line">  shellSort(arr);</span><br></pre></td></tr></table></figure>

<h2 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h2><p>堆是具有以下性质的二叉树：每个结点的值都大于或等于其左右孩子结点的值，称为大顶堆；或者每个结点的值都小于或等于其左右孩子结点的值，称为小顶堆。</p>
<p>由于记录的比较与交换是跳跃式进行，因此堆排序也是一种不稳定的排序方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*堆排序 */</span></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">      *<span class="doctag">@Description</span>:堆排序</span></span><br><span class="line"><span class="comment">      *<span class="doctag">@param </span>arr </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">headSort</span>(<span class="params">arr</span>)</span>&#123;</span><br><span class="line">        buildHeap(arr);<span class="comment">//构建堆</span></span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=len<span class="number">-1</span>;i&gt;<span class="number">0</span>;i--)&#123;</span><br><span class="line">            swap(arr,<span class="number">0</span>,i);<span class="comment">//交换堆的第一个元素和最后一个元素</span></span><br><span class="line">            heapify(arr,i);<span class="comment">//调整堆</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> arr;</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:创建堆</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param <span class="variable">arr</span></span></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">buildHeap</span>(<span class="params">arr</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">if</span>(len == <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="built_in">Math</span>.floor(len/<span class="number">2</span>) - <span class="number">1</span>;i&gt;<span class="number">0</span>;i--)&#123;</span><br><span class="line">            heapify(arr,i);<span class="comment">//在构建堆时，就需要一个个地调整堆</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:调整堆</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param </span>arr 调整数组</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param </span>i 跟</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">heapify</span>(<span class="params">arr,i</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> left = <span class="number">2</span>*i+<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">var</span> right = <span class="number">2</span>*i+<span class="number">2</span>;</span><br><span class="line">        <span class="keyword">var</span> largest = i;</span><br><span class="line">        <span class="keyword">var</span> len = arr.length;</span><br><span class="line">        <span class="keyword">if</span>(left &lt;len &amp;&amp; arr[left]&gt;arr[largest])&#123;<span class="comment">//先判断左节点还否超出</span></span><br><span class="line">            largest=left;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(right &lt;len &amp;&amp; arr[right]&gt;largest)&#123;<span class="comment">//右节点是否超出 找出最大的子节点</span></span><br><span class="line">            largest=right;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(largest != i)&#123;</span><br><span class="line">            swap(arr,i,largest);<span class="comment">//交换 largrst为i，这里交换的是两者序数对应的值</span></span><br><span class="line">            heapify(arr,largest);</span><br><span class="line"><span class="comment">//递归调整，如果左侧为largest，那么将左侧节点提上去，会影响左侧子树的原本正确排序，因此。递归调整左侧；递归调用的参数是，为最大的那一个</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * </span></span><br><span class="line"><span class="comment">          *<span class="doctag">@Description</span>:交换</span></span><br><span class="line"><span class="comment">          *<span class="doctag">@param <span class="variable">arr</span></span></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">swap</span>(<span class="params">arr,i,j</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> temp=arr[i];</span><br><span class="line">        arr[i] = arr[j];</span><br><span class="line">        arr[j] = temp;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h2><p>归并排序采用的是分治的思想，首先是“分”，将一个数组反复二分为两个小数组，</p>
<p>直到每个数组只有一个元素；其次是“治”，从最小数组开始，两两按大小顺序合并，直到并为原始数组大小，下面是图解：</p>
<p>分”就是将原始数组逐次二分，直到每个数组只剩一个元素，一个元素的数组自然是有序的，所以就可以开始“治”的过程了。</p>
<p>时间复杂度分析：</p>
<p>分的过程需要三步：log8 = 3，而每一步都需要遍历一次8个元素，所以8个元素共需要运行 8log8 次指令，那么对于 n 个元素，时间复杂度为 O(nlogn)。</p>
<p>“治”实际上是将已经有序的数组合并为更大的有序数组。那怎么做呢?就是创建一个新数组，比较left[0]和right[0] ，那个比较小就将那个的值放进新数组，</p>
<p>然后再继续比较left[0]和right[1]，或者是left[1]和right[0]。可以看出数组left，right都只需遍历一遍，所以对两个有序数组的排序的时间复杂度为O(n)。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mergeSort</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> len = arr.length</span><br><span class="line">    <span class="keyword">if</span> (len &lt; <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> arr</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> middle = <span class="built_in">Math</span>.floor(len/<span class="number">2</span>)</span><br><span class="line">    <span class="comment">//拆分成两个子数组</span></span><br><span class="line">    <span class="keyword">let</span> left =  arr.slice(<span class="number">0</span>, middle)</span><br><span class="line">    <span class="keyword">let</span> right = arr.slice(middle,len)</span><br><span class="line">    <span class="comment">//递归拆分</span></span><br><span class="line">    <span class="keyword">let</span> mergeSortLeft = mergeSort(left)</span><br><span class="line">    <span class="keyword">let</span> mergeSortRight = mergeSort(right)</span><br><span class="line">    <span class="comment">//合并</span></span><br><span class="line">    <span class="keyword">return</span> merge( mergeSortLeft,mergeSortRight)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> merge = <span class="function">(<span class="params">left, right</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = [];</span><br><span class="line">    <span class="keyword">while</span> (left.length &amp;&amp; right.length) &#123;</span><br><span class="line">        <span class="comment">// 注意: 判断的条件是小于或等于，如果只是小于，那么排序将不稳定.</span></span><br><span class="line">        <span class="keyword">if</span> (left[<span class="number">0</span>] &lt;= right[<span class="number">0</span>]) &#123;</span><br><span class="line">            result.push(left.shift()); <span class="comment">//每次都要删除left或者right的第一个元素，将其加入result中</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            result.push(right.shift());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//将剩下的元素加上</span></span><br><span class="line">    <span class="keyword">while</span> (left.length) result.push(left.shift());</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (right.length) result.push(right.shift());</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h2><p>希尔排序相当于是直接插入排序的升级，它们同属于插入排序类；堆排序相当于简单选择排序的升级，它们同属于选择排序类；而快速排序就是冒泡排序的升级，同属于交换排序类。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*快速排序</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> quickSort = <span class="function"><span class="keyword">function</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    　　<span class="keyword">if</span> (arr.length &lt;= <span class="number">1</span>) &#123; <span class="keyword">return</span> arr; &#125;</span><br><span class="line">    　　<span class="keyword">var</span> pivotIndex = <span class="built_in">Math</span>.floor(arr.length / <span class="number">2</span>);<span class="comment">//math.floor是-对数值的向下取整</span></span><br><span class="line">    　　<span class="keyword">var</span> pivot = arr.splice(pivotIndex, <span class="number">1</span>)[<span class="number">0</span>];</span><br><span class="line">    　　<span class="keyword">var</span> left = [];</span><br><span class="line">    　　<span class="keyword">var</span> right = [];</span><br><span class="line">    　　<span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arr.length; i++)&#123;</span><br><span class="line">    　　　　<span class="keyword">if</span> (arr[i] &lt; pivot) &#123;</span><br><span class="line">    　　　　　　left.push(arr[i]);</span><br><span class="line">    　　　　&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    　　　　　　right.push(arr[i]);</span><br><span class="line">    　　　　&#125;</span><br><span class="line">    　　&#125;</span><br><span class="line">    　　<span class="keyword">return</span> quickSort(left).concat([pivot], quickSort(right));</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> quickSort = <span class="function"><span class="keyword">function</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (arr.length &lt;= <span class="number">1</span>) <span class="keyword">return</span> arr;</span><br><span class="line">    <span class="keyword">let</span> midIndex = <span class="built_in">Math</span>.floor(arr.length / <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">let</span> mid = arr.splice(midIndex, <span class="number">1</span>)[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">let</span> left = [];</span><br><span class="line">    <span class="keyword">let</span> right = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (arr[i] &lt; mid) &#123;</span><br><span class="line">            left.push(arr[i]);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            right.push(arr[i]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> quickSort(left).concat([mid], quickSort(right));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*简单改进后的快排 */</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 快排改进——黄佳新</span></span><br><span class="line">    <span class="keyword">var</span> devide_Xin = <span class="function"><span class="keyword">function</span> (<span class="params">array, start, end</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(start &gt;= end) <span class="keyword">return</span> array;</span><br><span class="line">        <span class="keyword">var</span> baseIndex = <span class="built_in">Math</span>.floor((start + end) / <span class="number">2</span>), <span class="comment">// 基数索引</span></span><br><span class="line">             i = start,</span><br><span class="line">             j = end;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (i &lt;= j) &#123;</span><br><span class="line">            <span class="keyword">while</span> (array[i] &lt; array[baseIndex]) &#123;</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (array[j] &gt; array[baseIndex])  &#123;</span><br><span class="line">                j--;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(i &lt;= j) &#123;</span><br><span class="line">                <span class="keyword">var</span> temp = array[i];</span><br><span class="line">                array[i] = array[j];</span><br><span class="line">                array[j] = temp;</span><br><span class="line">                i++;</span><br><span class="line">                j--;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> quickSort_Xin = <span class="function"><span class="keyword">function</span> (<span class="params">array, start, end</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(array.length &lt; <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> array;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> index = devide_Xin(array, start, end);</span><br><span class="line">        <span class="keyword">if</span>(start &lt; index <span class="number">-1</span>) &#123;</span><br><span class="line">            quickSort_Xin(array, start, index - <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(end &gt; index) &#123;</span><br><span class="line">            quickSort_Xin(array, index, end);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> array;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/28/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E5%A4%A7%E8%AF%9D%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/28/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E5%A4%A7%E8%AF%9D%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" class="post-title-link" itemprop="url">大话数据结构</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-28 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-28T12:18:39+08:00">2021-09-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:28:22" itemprop="dateModified" datetime="2021-11-03T16:28:22+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">设计模式</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>数据结构：是相互之间存在一种或多种特定关系的数据元素的集合。</p>
<p>程序设计 = 数据结构 + 算法。</p>
<p>数据结构可以分为逻辑结构与物理结构。</p>
<p>逻辑结构：是指数据对象中数据元素之间的相互关系；可分为以下四种：</p>
<p>集合结构：集合结构中的数据元素处理同属于一个集合外，并无其他关系。线性结构：线性结构中数据元素为一对一的关系。树形结构：一对多的层次关系。图形结构：多对多的关系。</p>
<p>物理结构：是指数据的逻辑结构在计算机中的存储形式。</p>
<p>物理结构分为：顺序存储结构、链式存储结构。</p>
<h1 id="线性表"><a href="#线性表" class="headerlink" title="线性表"></a>线性表</h1><p>线性表：零个或者多个数据元素的有限序列。</p>
<h2 id="顺序存储结构"><a href="#顺序存储结构" class="headerlink" title="顺序存储结构"></a>顺序存储结构</h2><p>线性表的顺序存储结构：指的是用一段地址连续的存储单元依次存储线性表的数据元素。</p>
<p>顺序存储结构类似于数组的结构，其地址的计算方法跟元素的index序号，以及首元素的地址数组头地址均相关。</p>
<p>线性表的顺序存储结构，存、读数据的时间复杂度均为O(1)；而插入、删除的时间复杂度均为O(n)。</p>
<p>优点：1、无须为表示表内元素的逻辑关系，而额外增加存储空间；2、可快速存取表内任一位置元素；</p>
<p>缺点：1、插入和删除操作需要移动大量元素；2、当线性表长度变化较大时，难以确定存储空间的容量；3、容易造成存储空间的碎片。</p>
<h2 id="链式存储结构"><a href="#链式存储结构" class="headerlink" title="链式存储结构"></a>链式存储结构</h2><p>正是由于顺序存储结构的不足，因此诞生了链式存储结构。</p>
<p>在链式结构中，除了要存储数据元素信息外，还要存储它的后继元素的存储地址，分为数据域与指针域。对于单链表，通常为了操作的方便，我们会自己创建一个头指针与头节点来放在链表的最前面。</p>
<h3 id="循环链表"><a href="#循环链表" class="headerlink" title="循环链表"></a>循环链表</h3><p>将单链表中终端结点的指针端由空指针改为指向头结点，就使整个单链表形成了一个环，这个头尾相接的链表称为循环链表。</p>
<h3 id="双向链表"><a href="#双向链表" class="headerlink" title="双向链表"></a>双向链表</h3><p>双向链表是在单链表的每个节点中，再设置一个指向其前驱节点的指针域。</p>
<h1 id="栈与队列"><a href="#栈与队列" class="headerlink" title="栈与队列"></a>栈与队列</h1><h2 id="栈"><a href="#栈" class="headerlink" title="栈"></a>栈</h2><p>栈<strong>stack</strong>是限定仅在表尾进行插入和删除操作的线性表；允许插入、删除的一端称为栈顶，简称LIFO结构。（Last In First Out）。push进栈，pop出栈。</p>
<h3 id="顺序存储结构-1"><a href="#顺序存储结构-1" class="headerlink" title="顺序存储结构"></a>顺序存储结构</h3><p>其实就是线性表顺序存储的简化版，一般用数组来实现。同时，可以有多个栈来共享空间的操作。</p>
<h3 id="链式存储结构-1"><a href="#链式存储结构-1" class="headerlink" title="链式存储结构"></a>链式存储结构</h3><p>栈只用栈顶来做插入和删除操作，用于单链表有头指针，而栈顶指针也是必须的，因此其实可以合二为一。</p>
<h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3><p>递归：我们把一个直接调用自己或通过一系列的调用语句间接调用自己的函数，称为递归函数。递归的关键在于其推出条件，每个递归至少规定一个条件，满足时递归不再进行，即不引用自身而是返回值退出。</p>
<p>它通常把一个大型的复杂的问题转化为一个与原问题相似的规模较小的问题来解决,可以极大的减少代码量.递归的能力在于用有限的语句来定义对象的无限集合。</p>
<p>递归的关键：递归关系与递归终止条件。（其他的扔给递归）</p>
<p>1、找整个递归的终止条件：递归应该在什么时候结束？</p>
<p>2、找返回值：应该给上一级返回什么信息？</p>
<p>3、本级递归应该做什么：在这一级递归中，应该完成什么任务？</p>
<p>迭代:利用变量的原值推算出变量的一个新值.如果递归是自己调用自己的话,迭代就是A不停的调用B。</p>
<p>递归中一定有迭代,但是迭代中不一定有递归,大部分可以相互转换.能用迭代的不用递归,递归调用函数,浪费空间,并且递归太深容易造成堆栈的溢出。</p>
<p>逆波兰表达式：其实就是后缀表达式。例如：”9 + (3 - 1) * 3 + 10 ➗ 2”。用后缀表达式为”9 3 1 - 3 * + 10 2 / +”。</p>
<p>规则：从左往右遍历表达式的每个数字和符号，遇到数字则先进栈，遇到符号，则将处于栈顶的两个数字出栈，进行运算，并将运算结果入栈；一直到最终获得结果。</p>
<p>下面的代码用栈实现：由逆波兰表达式来求值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string[]&#125;</span> <span class="variable">tokens</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> evalRPN = <span class="function"><span class="keyword">function</span> (<span class="params">tokens</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> calculate = <span class="function">(<span class="params">num1, num2, operator</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">switch</span> (operator) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"+"</span>:</span><br><span class="line">        <span class="keyword">return</span> num1 + num2;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"-"</span>:</span><br><span class="line">        <span class="keyword">return</span> num1 - num2;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"*"</span>:</span><br><span class="line">        <span class="keyword">return</span> num1 * num2;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"/"</span>:</span><br><span class="line">        <span class="comment">// js 这里要用parseInt</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">parseInt</span>(num1 / num2, <span class="number">10</span>);</span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">let</span> stack = <span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> a <span class="keyword">of</span> tokens) &#123;</span><br><span class="line">    <span class="keyword">switch</span> (a) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"+"</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"-"</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"*"</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"/"</span>:</span><br><span class="line">        <span class="keyword">let</span> num1 = stack.pop();</span><br><span class="line">        <span class="keyword">let</span> num2 = stack.pop();</span><br><span class="line">        <span class="comment">// 注意下面调用calculate函数时第一个参数是num2而非num1</span></span><br><span class="line">        stack.push(calculate(num2, num1, a));</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">        stack.push(<span class="built_in">parseInt</span>(a, <span class="number">10</span>));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> stack.pop();</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>下面的代码使用两个栈将常用的中缀表达式转变为逆波兰表达式。</p>
<p>规则：从左到右遍历中缀表达式的每个数字和符号，若是数字就输出，即成为后缀表达式的一部分；若是符号，则判断其与栈顶符号的优先级，是右括号或者优先级不高于</p>
<p>1、创建两个栈s1，s2；s1用来存储运算符；s2用来存储中间结果</p>
<p>2、遍历表达式：当遇到数字时，推入s2</p>
<p>当遇到运算符时：若s1为空，或s1栈顶非运算符即 ( 和 ) ，推入s1；</p>
<p>与s1栈顶运算符比较：低于栈顶：推入s1；等于栈顶：推入s2；高于栈顶：弹出栈顶，将栈顶推入s2，循环直到该运算符弹入任意栈</p>
<p>3、处理 ( 和 )：</p>
<p>如果为 (，推入s1；如果为 ) ，将s1的栈顶不断的出栈并入栈到s2中，直到s1栈顶为 ( 时停止，并将 ( 出栈丢弃；</p>
<p>重复 2 里面的所有过程，直到表达式遍历结束；</p>
<p>将s2中的栈顶依次出栈并入栈到s1中；</p>
<p>将s1中的栈顶依次出栈并输出，即得到后缀表达式（逆波兰式）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">infixToSuffix</span>(<span class="params">infix</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> symbol = [],</span><br><span class="line">    value = [],</span><br><span class="line">    res = <span class="string">''</span></span><br><span class="line">  infix.split(<span class="string">''</span>).forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">switch</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="regexp">/\d/</span>.test(item):</span><br><span class="line">        value.push(item)</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> <span class="regexp">/[+\-*/]/</span>.test(item):</span><br><span class="line">        <span class="keyword">while</span> (symbol.length + <span class="number">1</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (!symbol.length || !<span class="regexp">/[+\-*/]/</span>.test(symbol[symbol.length - <span class="number">1</span>])) &#123;</span><br><span class="line">            <span class="comment">// 栈顶为空或非运算符</span></span><br><span class="line">            symbol.push(item) <span class="comment">// 弹入栈1</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span> (<span class="regexp">/[*/]/</span>.test(item) &amp;&amp; <span class="regexp">/[+\-]/</span>.test(symbol[symbol.length - <span class="number">1</span>])) &#123;</span><br><span class="line">            <span class="comment">// 比栈顶低</span></span><br><span class="line">            symbol.push(item) <span class="comment">// 弹入栈1</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span> (<span class="regexp">/[+\-]/</span>.test(item) &amp;&amp; <span class="regexp">/[*/]/</span>.test(symbol[symbol.length - <span class="number">1</span>])) &#123;</span><br><span class="line">            <span class="comment">// 比栈顶高</span></span><br><span class="line">            value.push(symbol.pop()) <span class="comment">// 弹出栈顶，栈顶弹入栈2</span></span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="comment">// 等于栈顶</span></span><br><span class="line">          value.push(item) <span class="comment">// 弹入栈2</span></span><br><span class="line">          <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> <span class="regexp">/\(/</span>.test(item):</span><br><span class="line">        symbol.push(item)</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> <span class="regexp">/\)/</span>.test(item):</span><br><span class="line">        <span class="keyword">while</span> (symbol.length) &#123;</span><br><span class="line">          <span class="keyword">let</span> mid = symbol.pop()</span><br><span class="line">          <span class="keyword">if</span> (mid !== <span class="string">'('</span>) &#123;</span><br><span class="line">            value.push(mid)</span><br><span class="line">          &#125; <span class="keyword">else</span> <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">while</span> (value.length) &#123;</span><br><span class="line">    symbol.push(value.pop())</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">while</span> (symbol.length) &#123;</span><br><span class="line">    res += symbol.pop()</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(infixToSuffix(<span class="string">'(3+4)*5-6'</span>)) <span class="comment">// 34+5*6-</span></span><br><span class="line"><span class="built_in">console</span>.log(infixToSuffix(<span class="string">'1+2*3+(4*5+6)*7'</span>)) <span class="comment">// 123*+45*6+7*+</span></span><br></pre></td></tr></table></figure>

<h2 id="队列"><a href="#队列" class="headerlink" title="队列"></a>队列</h2><p>队列是只允许在一端进行插入操作，而在另一端进行删除操作的线性表。队列是一种先进先出的线性表FIFO。允许插入的一端成为队尾，允许删除的一段称为队头。</p>
<p>循环队列：队列的头尾相连的顺序存储结构称为循环队列。循环队列使得队头和队尾</p>
<p>队列的链式存储结构，其实就是线性表的单链表。</p>
<h2 id="串"><a href="#串" class="headerlink" title="串"></a>串</h2><p>串是由零个或者多个字符组成的有限序列，又名叫字符串。</p>
<p>串的模式匹配：定位子串在主串中的位置。最快速的算法是KMP模式匹配算法。</p>
<p>KMP算法的关键在于其next数组的选取与推导。</p>
<h3 id="KMP算法"><a href="#KMP算法" class="headerlink" title="KMP算法"></a>KMP算法</h3><h1 id="树"><a href="#树" class="headerlink" title="树"></a>树</h1><p>树本身其实就是一个递归的定义。1、树的根节点是唯一的，不可能出现多个根节点。2、子树的个数没有限制，但它们一定是互不相交的。</p>
<p>树的结点包括一个数据元素与若干指向其子树的分支。结点拥有的子树数称为结点的度degree。度为0的结点称为叶结点或者终端结点。</p>
<p>如果将树中所有结点的各个子树看作从左到右是有次序的，不能互换的，则称该树为有序树，否则为无序树。</p>
<p>满二叉树：一个二叉树如果所有的分支结点都存在左子树和右子树，并且所有叶子都在同一层上，这样的二叉树称为满二叉树。</p>
<p>完全二叉树：对一棵具有n个结点的二叉树按照层序编号，如果编号为i的结点与同样深度的满二叉树中编号为i的结点位置完全相同，则该二叉树称为完全二叉树。</p>
<p>完全二叉树的特点：1、叶子结点只出现在最后两层，2、最下层结点一定位于左部连续位置，3、倒数第二层，若有叶子节点，一定位于右部连续位置；4、若结点度为1，则只有左孩子，无右孩子；5、同样结点树的二叉树，完全二叉树深度最小。</p>
<h2 id="二叉树"><a href="#二叉树" class="headerlink" title="二叉树"></a>二叉树</h2><h3 id="二叉树性质"><a href="#二叉树性质" class="headerlink" title="二叉树性质"></a>二叉树性质</h3><p>1、在二叉树的第i层上至多有2^（i-1）个结点；</p>
<p>2、深度为k的二叉树至多有2^k - 1个结点；</p>
<p>3、对任何一棵二叉树T，如果其终端结点数为n，度为2的结点数为m，则n = m + 1；（终端结点数其实就是叶子结点数）。推论方式：总结点数all = n + m + l；l是度为1的结点数。同理，根据连线数可知，由于根节点只有分支出去，没有分支进入，所以分支线总数为结点总数-1= all - 1。而分支线总数又等于l + 2m。因此n + m + l - 1= l + 2m。n = m + 1。</p>
<p>4、具有n个结点的完全二叉树的深度为log2n + 1。通过深度k的完全二叉树结点数反推即可。</p>
<p>5、如果对一棵有n个结点的完全二叉树的结点按层序编号，对于任一结点有：</p>
<p>i=1时，则结点i为二叉树的根，无双亲；如果i &gt; 1，则其双亲是结点 i/2。</p>
<p>如果2i &gt; n，则结点i无左孩子；否则其左孩子为结点2i</p>
<p>如果2i+1 &gt; n，则结点i无右孩子；否则其右孩子为结点2i + 1。</p>
<p>这个性质在堆排序中十分常见，用于寻找结点的双亲结点。</p>
<h3 id="存储结构"><a href="#存储结构" class="headerlink" title="存储结构"></a>存储结构</h3><p>二叉树的顺序存储结构通常用数组来实现，通过数组的下标来体现结点之间的逻辑关系。通常这种情况用于二叉堆比较多，堆排序其实就是这样的思路。</p>
<p>二叉链表：二叉树的每个结点最多有两个孩子，所以为它设计一个数据域和两个指针域是自然的想法。</p>
<h3 id="遍历"><a href="#遍历" class="headerlink" title="遍历"></a>遍历</h3><h4 id="前、中、后序遍历"><a href="#前、中、后序遍历" class="headerlink" title="前、中、后序遍历"></a>前、中、后序遍历</h4><p>前序遍历的代码如下：包括递归实现与迭代实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//递归实现如下</span></span><br><span class="line"><span class="keyword">const</span> preorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="comment">//定义一个数组存储遍历结果</span></span><br><span class="line">    <span class="keyword">const</span> traversal = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">//定义递归函数，用于前序遍历每一轮二叉树</span></span><br><span class="line">        <span class="keyword">if</span> (root !== <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="comment">//递归的关键：退出条件-节点为空</span></span><br><span class="line">            res.push(root.val);</span><br><span class="line">            traversal(root.left);</span><br><span class="line">            traversal(root.right);</span><br><span class="line">            <span class="comment">//依次递归遍历左右子树</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    traversal(root);</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*迭代的实现如下，维护一个栈来实现先序遍历</span></span><br><span class="line"><span class="comment">首先根入栈将根节点出栈，将根节点值放入结果数组中</span></span><br><span class="line"><span class="comment">然后遍历左子树、右子树，因为栈是先入后出，所以，我们先右子树入栈，然后左子树入栈</span></span><br><span class="line"><span class="comment">继续出栈（左子树被出栈）</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">const</span> preorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">const</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line">    <span class="comment">//类似于链表中定义头节点的行为，后续用node进行指针遍历操作</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (node || stack.length) &#123;</span><br><span class="line">        <span class="comment">//只有node为空，且栈内值均出栈时，整个迭代流程才结束</span></span><br><span class="line">        <span class="keyword">if</span> (node) &#123;</span><br><span class="line">            <span class="comment">//向左一直找到最下方的左叶子节点</span></span><br><span class="line">            res.push(node.val);</span><br><span class="line">            stack.push(node.right);</span><br><span class="line">            stack.psuh(node.left);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            node = stack.pop();</span><br><span class="line">            <span class="comment">//当找到最下方的左叶子节点时，则栈顶结点出栈，作为node继续迭代。</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>中序遍历的代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> inorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = []</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traversal</span> (<span class="params">root</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (root !== <span class="literal">null</span>) &#123;</span><br><span class="line">        traversal(root.left)</span><br><span class="line">        res.push(root.val)</span><br><span class="line">        traversal(root.right)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    traversal(root)</span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">/*同样可以通过维护一个栈来使用迭代算法，从而实现二叉树的中序遍历 </span></span><br><span class="line"><span class="comment">1、每次先看node结点存在与否，存在则入栈，并跳左结点，从而先遍历左子树；</span></span><br><span class="line"><span class="comment">2、直到node结点不存在时，则出栈上一个作为node，此时代表左子树已经全部遍历完成，则需要将跟结点值放入结果数组，并跳右节点，遍历右子树</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> inorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">const</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (node || stack.length) &#123;</span><br><span class="line">        <span class="keyword">if</span> (node) &#123;</span><br><span class="line">            <span class="comment">//存在node结点，则先入栈并跳左结点，从而遍历左子树</span></span><br><span class="line">            stack.push(node);</span><br><span class="line">            node = node.left;</span><br><span class="line">            <span class="comment">//遍历左边的子树,每次只入栈一个node即可</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//node不存在时，则左子树遍历完成，结点值放入结果，跳右节点，从而遍历右子树。</span></span><br><span class="line">            node = stack.pop();</span><br><span class="line">            res.push(node.val);</span><br><span class="line">            <span class="comment">//由于是中序遍历，</span></span><br><span class="line">            node = node.right;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>后序遍历的代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> postorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = []</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traversal</span> (<span class="params">root</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (root !== <span class="literal">null</span>) &#123;</span><br><span class="line">        traversal(root.left)</span><br><span class="line">        traversal(root.right)</span><br><span class="line">        res.push(root.val)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    traversal(root)</span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*同样通过维护一个栈来使用迭代算法，从而实现二叉树的后序遍历</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">方法一：使用队列辅助迭代实现</span></span><br><span class="line"><span class="comment">解题思路： 后序遍历与前序遍历不同的是：</span></span><br><span class="line"><span class="comment">后序遍历是左右根</span></span><br><span class="line"><span class="comment">而前序遍历是根左右</span></span><br><span class="line"><span class="comment">如果我们把前序遍历的 list.push(node.val) 变更为 list.unshift(node.val) （遍历结果逆序），那么遍历顺序就由 根左右 变更为 右左根</span></span><br><span class="line"><span class="comment">然后我们仅需将 右左根 变更为 左右根 即可完成后序遍厉。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> postorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">const</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (node || stack.length) &#123;</span><br><span class="line">        <span class="keyword">if</span> (node) &#123;</span><br><span class="line">            res.unshift(node.val);</span><br><span class="line">            stack.push(node.left);</span><br><span class="line">            node = node.right;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            node = stack.pop();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="BFS与DFS"><a href="#BFS与DFS" class="headerlink" title="BFS与DFS"></a>BFS与DFS</h4><p>层序遍历代码如下：层序遍历的本质其实就是二叉树的BFS，广度优先遍历。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">递归传递的参数除了头节点以外，一定要加上当前的层数，这样才能够正确地生成数组 </span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">  <span class="keyword">var</span> levelOrder = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = []</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traversal</span> (<span class="params">root, depth</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (root !== <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!res[depth]) &#123;</span><br><span class="line">          res[depth] = []</span><br><span class="line">        &#125;</span><br><span class="line">        traversal(root.left, depth + <span class="number">1</span>)</span><br><span class="line">        res[depth].push(root.val)</span><br><span class="line">        traversal(root.right, depth + <span class="number">1</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    traversal(root, <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//迭代的代码实现方式如下：</span></span><br><span class="line"><span class="keyword">var</span> levelOrder = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//二叉树的层序遍历</span></span><br><span class="line">    <span class="keyword">let</span> res=[],queue=[];</span><br><span class="line">    queue.push(root);</span><br><span class="line">    <span class="keyword">if</span>(root===<span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span>(queue.length!==<span class="number">0</span>)&#123;</span><br><span class="line">        <span class="comment">// 记录当前层级节点数</span></span><br><span class="line">        <span class="keyword">let</span> length=queue.length;</span><br><span class="line">        <span class="comment">//存放每一层的节点 </span></span><br><span class="line">        <span class="keyword">let</span> curLevel=[];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span>;i&lt;length;i++)&#123;</span><br><span class="line">            <span class="keyword">let</span> node=queue.shift();</span><br><span class="line">            curLevel.push(node.val);</span><br><span class="line">            <span class="comment">// 存放当前层下一层的节点</span></span><br><span class="line">            node.left &amp;&amp; queue.push(node.left);</span><br><span class="line">            node.right &amp;&amp; queue.push(node.right);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//把每一层的结果放到结果数组</span></span><br><span class="line">        res.push(curLevel);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>深度优先遍历DFS的代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> dfs = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> ;</span><br><span class="line">    &#125;</span><br><span class="line">    dfs(root.left);</span><br><span class="line">    dfs(root.right);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//下面是一个简单的全排列的代码，其实本质上就是一个回溯</span></span><br><span class="line"><span class="keyword">var</span> permute = <span class="function"><span class="keyword">function</span>(<span class="params">nums</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="comment">//递归的关键：递归关系与递归终止条件。（其他的扔给递归）</span></span><br><span class="line">    <span class="comment">//1、找整个递归的终止条件：递归应该在什么时候结束？</span></span><br><span class="line">    <span class="comment">//2、找返回值：应该给上一级返回什么信息？</span></span><br><span class="line">    <span class="comment">//3、本级递归应该做什么：在这一级递归中，应该完成什么任务？</span></span><br><span class="line">    <span class="comment">//本题中，应当传递给递归的参数最少可以只有1个，但用一个map或数组去记录已加入路径的数字，</span></span><br><span class="line">    <span class="comment">//而不是调用 path.includs 类似的库函数，导致每次都是 O(n) 的查找时间。</span></span><br><span class="line">    <span class="keyword">const</span> dfs = <span class="function">(<span class="params">path, set</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (path.length === nums.length) &#123;</span><br><span class="line">            res.push(path.slice());</span><br><span class="line">            <span class="keyword">return</span>;<span class="comment">//由于数组是引用类型，因此每次返回必须返回新的数组，避免后续修改bfs对当前返回造成的影响</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!<span class="keyword">set</span>[i]) &#123;</span><br><span class="line">                path.push(nums[i]);</span><br><span class="line">                <span class="keyword">set</span>[i] = true;</span><br><span class="line">                dfs(path, <span class="keyword">set</span>);</span><br><span class="line"></span><br><span class="line">                //回溯</span><br><span class="line">                path.pop();</span><br><span class="line">                <span class="keyword">set</span>[i] = false;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    dfs([], []);</span><br><span class="line"></span><br><span class="line">    return res;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>下面是一个获取二叉树所有的路径的题目，本质上也是一个二叉树的DFS遍历</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> binaryTreePaths = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> paths = [];</span><br><span class="line">    <span class="keyword">const</span> construct_paths = <span class="function">(<span class="params">root, path</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (root) &#123;</span><br><span class="line">            <span class="comment">//递归的结束条件是root为空</span></span><br><span class="line">            path += root.val.toString();</span><br><span class="line">            <span class="keyword">if</span> (root.left === <span class="literal">null</span> &amp;&amp; root.right === <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="comment">//即当前节点为叶子节点时,这是符合要求，路径到最后的条件</span></span><br><span class="line">                paths.push(path);<span class="comment">//则此时将路径进栈，再去找其他的路径。</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                path += <span class="string">"-&gt;"</span>;<span class="comment">//当节点不是叶子节点时，继续进行递归遍历</span></span><br><span class="line">                construct_paths(root.left, path);</span><br><span class="line">                construct_paths(root.right, path);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    construct_paths(root, <span class="string">""</span>);</span><br><span class="line">    <span class="keyword">return</span> paths;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>下面是一个：二叉树的节点和为某一个值得路径。剑指offer34题，找出从根节点到叶子节点路径总和等于给定目标和得路径。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*代码本质上其实就是一个DFS+剪枝的过程</span></span><br><span class="line"><span class="comment">1、剪枝：空树时则返回；</span></span><br><span class="line"><span class="comment">2、由于路径要从根节点到叶子节点，因此符合要求的条件有：路径和+该点=target；左右子树均为空;</span></span><br><span class="line"><span class="comment">3、回溯代码的一般步骤：先处理节点，然后DFS，最后回溯。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">const</span> pathSum = <span class="function"><span class="keyword">function</span>(<span class="params">root, target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> res = [];</span><br><span class="line">    <span class="keyword">let</span> path = [];</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">DFS</span>(<span class="params">root, sum</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!root) <span class="keyword">return</span>; <span class="comment">//剪枝的条件为此时为空节点</span></span><br><span class="line">        <span class="keyword">if</span> (!root.left &amp;&amp; !root.right &amp;&amp; (sum + root.val == target)) &#123;</span><br><span class="line">            res.push([...path, root.val]);</span><br><span class="line">            <span class="keyword">return</span> ;</span><br><span class="line">        &#125;</span><br><span class="line">        path.push(root.val);</span><br><span class="line">        DFS(root.left, sum + root.val);</span><br><span class="line">        DFS(root.right, sum + root.val);</span><br><span class="line">        path.pop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>leetcode124题：二叉树中的最大路径和。</p>
<p>这个路径被定义为一条从树中任一节点触发，沿父节点-子节点连接，达到任意节点的序列。</p>
<p>思路：1、路径走到一个节点，有三个选择，停下、走左结点、走右节点。递归很容易来解决这种重复性问题。注意：不能回头走分支，因为路径不能重叠。</p>
<p>定义递归函数：对于一个父节点，它关心自己走入一个子树，从中捞取的最大收益，不关心具体怎么走。</p>
<p>DFS：返回当前子树能向父节点提供的最大路径和，即Max(root.val, root.val + dfs(root.left), root.val + dfs(root.right))。即三种情况的最大值。</p>
<p>注意项：1、不能回头，导致路径重叠；2、遍历至null时，返回。3、若某个子树DFS结果为负，则直接排除。</p>
<p>一个子树内部最大路径和 = 左子树提供最大子树和 + 根节点 + 右子树最大路径和</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> maxPathSum = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> maxSum = <span class="built_in">Number</span>.MIN_SAFE_INTEGER;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> dfs = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (root == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="comment">//遍历到null节点时，收益为0</span></span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> left = dfs(root.left);<span class="comment">//左子树提供的最大路径和</span></span><br><span class="line">        <span class="keyword">const</span> right = dfs(root.right);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">const</span> innnerMaxSum = left + root.val + right;<span class="comment">//当前子树内部的最大路径和</span></span><br><span class="line">        maxSum = <span class="built_in">Math</span>.max(maxSum, innerMaxSum);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">const</span> outputMaxSum = root.val + <span class="built_in">Math</span>.max(<span class="number">0</span>, left, right);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> outputMaxSum &lt; <span class="number">0</span> ? <span class="number">0</span> : outputMaxSum;</span><br><span class="line">    &#125;;</span><br><span class="line">    </span><br><span class="line">    dfs(root);</span><br><span class="line">    <span class="keyword">return</span> maxSum;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="线索二叉树"><a href="#线索二叉树" class="headerlink" title="线索二叉树"></a>线索二叉树</h3><p>我们把这种指向前驱和后继的指针称为线索，而加上线索的二叉链表称为线索链表；相应的二叉树就称为线索二叉树。</p>
<p>我们对二叉树以某种次序遍历使其变成线索二叉树的过程，称为线索化。</p>
<h2 id="赫夫曼树"><a href="#赫夫曼树" class="headerlink" title="赫夫曼树"></a>赫夫曼树</h2><p>路径长度：从树中一个结点到另一个结点之间的分支，构成两个结点之间的路径，路径上的分支数目称作路径长度。</p>
<p>而树本身的路径长度就是：树根节点到每一个结点的路径长度之和。</p>
<p>如果对路径长度与结点都加上权值的话，带权路径长度WPL，WPL最小的二叉树称作赫夫曼树，又叫最优二叉树。</p>
<p>构造赫夫曼树的赫夫曼算法描述如下：</p>
<p>1、根据给定的n个权值{W1, W2, W3,…,Wn}构成n棵二叉树的集合F={T1,T2, … Tn},其中每棵二叉树Ti中只有一个带权为Wi根节点，其左右子树均为空。</p>
<p>2、在F中选取两棵根节点的权值最小的树作为左右子树，构造一棵新的二叉树，且置新得二叉树的根节点的权值为其左右子树上根节点的权值之和。</p>
<p>3、在F中删除这两棵树，同时将新得到的二叉树加入F中。</p>
<p>4、重复2、3步骤，直至F只含一棵树为止，这棵树就是赫夫曼树。</p>
<h1 id="图"><a href="#图" class="headerlink" title="图"></a>图</h1><p>图是一种相较于线性表与树，更加复杂的数据结构，在图形的结构中，结点之间的关系可以是任意的，图中任何两个数据元素之间都可能相关。</p>
<p>图中的数据元素称为顶点，而图中的连接线分为无向边与有向边，同样图按照有无方向可分为有向图与无向图。</p>
<p>图的存储结构：邻接矩阵与邻接表。</p>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/" class="post-title-link" itemprop="url">nodejs</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-25 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-25T12:18:39+08:00">2021-09-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:20:13" itemprop="dateModified" datetime="2021-11-03T16:20:13+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>之前也接触过node.js，但最近才想完全系统的入手实践node，因此想以狼书为着手点，开始入门node，以下其实更多的是看书后的总结与感悟。</p>
<p>最小功效原则：选择最适合的解决方案而不是最强的，语言的功效越弱，对于存储在语言中通的数据，我们能做的事情就越多。因此，语言结构越简单，进行数据分析与提取就越容易，</p>
<p>Node.js的本质：是JavaScript运行时环境，构建在V8引擎之上，会最终转译成C或者C++来执行，Node.js中的每个函数都是同步的，而I/O操作是异步的，所有由JS编写的函数I/O操作将会转义成C++的事件循环库来处理，隐藏了非阻塞I/O的具体细节，简化了并发编程模型。Node.js的目标是让并发编程更加地简单。 </p>
<p>Node.js是基于V8构建的，由其事件循环机制来分发I/O任务，最终工作线程会将任务放到线程池中执行，而事件循环只要等待执行结果就好了。在解决并发问题上，异步是最好的解决方案，其实就是可以类比为排队与叫号机制。</p>
<p>Node.js已经帮我们构建了类似的机制，写代码的过程就是取号的过程，由事件循环来接受处理，而真正执行操作的是具体线程池中的I/O任务。简化了并发编程，但也埋下了祸根。</p>
<p>Node.js的四个特点：适合构建web应用的、高性能的、简单的、可扩展的。</p>
<p>Node.js是基于CommonJS规范的实现，即每一个文件都是一个模块，每个模块内部代码的写法都必须遵守CommonJS规范，多文件调用的核心基于模块对外暴露接口和互相引用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Hello"</span>);</span><br><span class="line">    <span class="comment">//这里我们使用module.exports对外暴露一个匿名函数</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> hello = <span class="built_in">require</span>(<span class="string">'./hello_commonjs'</span>);</span><br><span class="line"><span class="comment">//这里通过require关键字来引用模块，由于在上面我们于模块中导出了一个匿名函数，所以可以直接调用。</span></span><br></pre></td></tr></table></figure>

<p>注：块作用域声明像let、const、function、class等在严格模式以外是不支持的，需要先在文件第一行加上use strict。</p>
<h1 id="更了不起的Node-js"><a href="#更了不起的Node-js" class="headerlink" title="更了不起的Node.js"></a>更了不起的Node.js</h1><h2 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h2><p>JS作为一个典型的多范式编程语言，最近其函数式编程概念开始流行，其要点如下：1、函数是第一等公民；2、函数柯里化：传递给函数一部分参数来调用2它，让它返回一个函数，从而去处理剩下的参数；3、为解决函数嵌套的问题，代码中使用了函数组合的方式，下面代码的calcAvgCost和flow函数都是典型的函数组合。</p>
<p>实例函数式编程代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.map(fn);</span><br><span class="line"><span class="keyword">const</span> prop = <span class="function"><span class="params">key</span> =&gt;</span> <span class="function"><span class="params">object</span> =&gt;</span> object[key];</span><br><span class="line"><span class="keyword">const</span> reduce = <span class="function">(<span class="params">fn, initial</span>) =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.reduce(fn, initial);</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">x, y</span>) =&gt;</span> x + y;</span><br><span class="line"><span class="keyword">const</span> sum = reduce(add, <span class="number">0</span>);</span><br><span class="line"><span class="keyword">const</span> filter = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.filter(fn);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> average = <span class="function"><span class="params">items</span> =&gt;</span> (</span><br><span class="line">    items.length === <span class="number">0</span> . ? <span class="number">0</span> : sum(items) / items.length</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> flow = <span class="function">(<span class="params">...fns</span>) =&gt;</span> <span class="function"><span class="params">x</span> =&gt;</span> (</span><br><span class="line">	fns.reduce(<span class="function">(<span class="params">result, fn</span>) =&gt;</span> fn(result), x)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> calcAvgCost = <span class="function">(<span class="params">items, filterFn = (</span>) =&gt;</span> <span class="literal">true</span>) =&gt; &#123;</span><br><span class="line">    flow(</span><br><span class="line">    	filter(filterFn),</span><br><span class="line">        map(prop(<span class="string">'price'</span>)),</span><br><span class="line">        average</span><br><span class="line">    )(items)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//calcAvgCost函数的用法如下代码所示</span></span><br><span class="line"><span class="keyword">const</span> items = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">''</span>&#125;</span><br><span class="line">]</span><br><span class="line"><span class="keyword">const</span> avgCost = calcAvgCost(items);</span><br></pre></td></tr></table></figure>

<p>函数柯里化的相关定义与应用如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 函数柯里化及其通用封装</span></span><br><span class="line"><span class="comment">柯里化就是，</span></span><br><span class="line"><span class="comment">把原来的函数 adder(3,5,6,7,8,9) ==&gt; adder(3)(5)(6)(7)(8)(9)()；</span></span><br><span class="line"><span class="comment">那么这么做的好处是什么呢？</span></span><br><span class="line"><span class="comment">延迟计算，何时想要结果了，直接adder()就行了</span></span><br><span class="line"><span class="comment">通常也成为部分求值，给函数分步传递参数，逐步缩小函数的适用范围，逐步求解的过程。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">如何实现柯里化函数</span></span><br><span class="line"><span class="comment">柯里化的定义，接收一部分参数，返回一个函数接收剩余参数，接收足够参数后，执行原函数。</span></span><br><span class="line"><span class="comment">我们已经知道了，当柯里化函数接收到足够参数后，就会执行原函数，</span></span><br><span class="line"><span class="comment">那么我们如何去确定何时达到足够的参数呢？</span></span><br><span class="line"><span class="comment">我们有两种思路：</span></span><br><span class="line"><span class="comment">1、通过函数的 length 属性，获取函数的形参个数，形参的个数就是所需的参数个数</span></span><br><span class="line"><span class="comment">2、在调用柯里化工具函数时，手动指定所需的参数个数</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">/*通用版本：curry 函数的第一个参数是要动态创建柯里化的函数，余下的参数存储在 args 变量中。</span></span><br><span class="line"><span class="comment">执行 curry 函数返回的函数接收新的参数与 args 变量存储的参数合并，并把合并的参数传入给柯里化了的函数。 </span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> args = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">var</span> newArgs = args.concat(<span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>));</span><br><span class="line">        <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, newArgs);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*bind函数；柯里化另一个典型的应用场景就是 bind 函数的实现。使用了函数柯里化的两个特点：参数复用和提前返回。*/</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.bind = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> fn = <span class="keyword">this</span>;</span><br><span class="line">	<span class="keyword">var</span> args = <span class="built_in">Array</span>.prototye.slice.call(<span class="built_in">arguments</span>);</span><br><span class="line">	<span class="keyword">var</span> context = args.shift();</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn.apply(context, args.concat(<span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)));</span><br><span class="line">	&#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*优化版：实现add(1)(2)(3)();只有在输入()时才计算值 */</span></span><br><span class="line"><span class="keyword">const</span> currying = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> args = [];</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">arguments</span>.length === <span class="number">0</span>) &#123;</span><br><span class="line">             <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, args);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">Array</span>.prototype.push.apply(args, [].slice.call(<span class="built_in">arguments</span>));</span><br><span class="line">            <span class="comment">//args.push([].slice.call(arguments));//用slice将类数组转换成数组，在合并至args上。</span></span><br><span class="line">            <span class="comment">//Array.prototype.push()添加一个或多个元素到数组的末尾，并返回数组新的长度（length 属性值）。利用该方法合并两个参数数组</span></span><br><span class="line">            <span class="keyword">return</span> f;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sum = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>;i &lt; <span class="built_in">arguments</span>.length; i++) &#123;</span><br><span class="line">        ans = ans + <span class="built_in">parseInt</span>(<span class="built_in">arguments</span>[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> sum1 = currying(sum);</span><br><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">100</span>,<span class="number">200</span>))</span><br><span class="line"><span class="built_in">console</span>.log(sum1(<span class="number">100</span>, <span class="number">200</span>)(<span class="number">300</span>)(<span class="number">200</span>));</span><br><span class="line"><span class="built_in">console</span>.log(sum1());</span><br><span class="line"></span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">函数柯里化是把接受多个参数的函数转变成接受一个单一参数(最初函数的第一个参数),</span></span><br><span class="line"><span class="comment">并且返回接受余下的参数而且返回结果的新函数的技术柯里化其实本身是固定一个可以预期的参数，并返回一个特定的函数，</span></span><br><span class="line"><span class="comment">处理批特定的需求。这增加了函数的适用性，但同时也降低了函数的适用范围。</span></span><br><span class="line"><span class="comment">1、提高适用性</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">//2、延迟执行：柯里化的另一个应用场景是延迟执行。不断的柯里化，累积传入的参数，最后执行。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*3、固定易变参数:柯里化特性决定了它这应用场景。</span></span><br><span class="line"><span class="comment">提前把易变因素，传参固定下来，生成一个更明确的应用函数。最典型的代表应用，是bind函数用以固定this这个易变对象。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">/*已知 fn 为一个预定义函数，实现函数 curryIt，调用之后满足如下条件：</span></span><br><span class="line"><span class="comment">1、返回一个函数 a，a 的 length 属性值为 1（即显式声明 a 接收一个参数）</span></span><br><span class="line"><span class="comment">2、调用 a 之后，返回一个函数 b, b 的 length 属性值为 1</span></span><br><span class="line"><span class="comment">3、调用 b 之后，返回一个函数 c, c 的 length 属性值为 1</span></span><br><span class="line"><span class="comment">4、调用 c 之后，返回的结果与调用 fn 的返回值一致</span></span><br><span class="line"><span class="comment">5、fn 的参数依次为函数 a, b, c 的调用参数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curryIt</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> a = <span class="function"><span class="keyword">function</span>(<span class="params">s1</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> b = <span class="function"><span class="keyword">function</span>(<span class="params">s2</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">let</span> c = <span class="function"><span class="keyword">function</span>(<span class="params">s3</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> fn(s1, s2, s3);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> c;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> b;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> a;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="单线程"><a href="#单线程" class="headerlink" title="单线程"></a>单线程</h2><p>单线程十分脆弱，随便一点异常就容易挂掉，但Node.js就是单线程的，却再线上高可用的项目中被频繁运用以应对并发，关键在于使用的方法。单线程的使用要点：1、单个应用实例可以适当捕获异常。2、单个应用崩溃后，用PM2重启；3、利用多核集群同时在一台服务器上启动多个实例；4、多台服务器可做多个集群。</p>
<h3 id="异常捕获"><a href="#异常捕获" class="headerlink" title="异常捕获"></a>异常捕获</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="params">ctx</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (ctx.path == <span class="string">'/good'</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx.body = <span class="string">'good'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    fs.readFile(<span class="string">'somefile.txt'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">        <span class="built_in">console</span>.log(data);</span><br><span class="line">        </span><br><span class="line">        ctx.body = <span class="string">'Hello Koa'</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            <span class="comment">//这里捕获不到readCallback函数抛出的异常</span></span><br><span class="line">            <span class="built_in">console</span>.log(e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'离开try/catch'</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">process.on(<span class="string">'uncaughtException'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用process.on('uncaughtException', function (err) &#123;&#125;)可以捕获异常并避免接口崩溃.</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">在fs.readFile的回调中加入try、catch后，当读取文件遇到异常时，就会直接抛出，而异常会被try、catch捕获，当前线程就不会因为异常而意外结束。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>异常捕获的注意事项：1、Node.js中同步代码才能够捕获异常，promise的处理需要使用Promise的异常处理方法。2、try、catch会影响性能，因此也要谨慎使用。</p>
<p>Node中有专门负责进程崩溃后应用自动重启的模块，名为forever；现在通常使用PM2来代替。</p>
<h3 id="集群"><a href="#集群" class="headerlink" title="集群"></a>集群</h3><p>小集群：现在的单台服务器大多是多核的，使用Cluster集群模块专门用于解决多核并发问题。</p>
<p>Nginx或HAProxy等集群都是一主多从的，主机的端口通过负载均衡算法将请求转发到Slave机器上，在一台机器上启动多个实例，原理也是类似。</p>
<p>这里通常都使用PM2进行统一的管理。</p>
<p>大集群：多台机器进行集群处理，同时通过负载均衡将流量分发到各个机器上，通过消除单点故障提升应用系统的可用性。常见的有Nginx、HAProxy、Tengine。</p>
<p>前端的所有请求都会落在负载层，再由负载层转发到负载中可用节点的服务器上。</p>
<h2 id="异步与回调"><a href="#异步与回调" class="headerlink" title="异步与回调"></a>异步与回调</h2><p>JavaScript现在通常使用Promise、async函数来进行回调地狱的解决，包括generator特性。</p>
<p>异步解决的处理中，首选async函数，其次使用Promise，Promise可以很好地价于callback与async。</p>
<h2 id="转译"><a href="#转译" class="headerlink" title="转译"></a>转译</h2><p>使用ES.next的特性进行开发，在生成环境里使用转译工具将ES.next特性转译为ES5。转译工具包括：babei、TypeScript、Traceur。</p>
<p>Delegate</p>
<p>在JS中可以将一个对象的方法、属性等委托给另一个对象。KOA的上下文对象ctx可以访问一些request和response上的方法、属性，原因在于request或者respomse上的方法、属性被委托给了ctx对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> delegate = <span class="built_in">require</span>(<span class="string">'delegates'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proto = &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line">delegate(proto, <span class="string">'response'</span>).method(<span class="string">'redirect'</span>)...access(<span class="string">'body'</span>)...</span><br><span class="line"><span class="comment">//将上面的代码委托给response的属性</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    ctx.body = <span class="string">'xxx'</span>;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>Only</p>
<p>在KOA的源码中总能看到toJSON()方法的实现，代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">toJSON() &#123;</span><br><span class="line">    <span class="keyword">return</span> only(<span class="keyword">this</span>, [</span><br><span class="line">        <span class="string">'method'</span>,</span><br><span class="line">        <span class="string">'url'</span>,</span><br><span class="line">        <span class="string">'header'</span></span><br><span class="line">    ])</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里的only是一个node.js模块，用于返回对象的白名单属性，尤其适用于类的方法非常多，但只想暴露部分属性的情况。</span></span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/24/node/%E6%95%B0%E6%8D%AE%E5%BA%93/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/24/node/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-title-link" itemprop="url">MongoDB数据库</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-24 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-24T12:18:39+08:00">2021-09-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:19:14" itemprop="dateModified" datetime="2021-11-03T16:19:14+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>在WEB应用中最常见的就是I/O操作，而只要涉及业务处理及数据持久化，就需要使用数据库。</p>
<p>关系型数据库：基础是关系代数，主要处理结构化数据，表连接在一起时会产生一个笛卡尔乘积。关系型数据库主要采用SQL（结构化查询语言）。例如MySQL。</p>
<p>非关系型数据库：主要用于解决四个问题：1、数据的高并发读/写；2、数据的高可用；3、海量数据的存储；4、实时分析。</p>
<p>所以非关系型数据库采用键值对形式存储，缓存的好处是极其明显的。</p>
<p>MongoDB是一个解与关系型数据建库和非关系型数据库之间的产品，是NoSQL中功能最丰富、最像关系型数据库的。MongoDB最大的特点是它的查询语言功能非常强大，其语法有点类似于面向对象的查询语言。</p>
<h2 id="模型"><a href="#模型" class="headerlink" title="模型"></a>模型</h2><p>MVC是一种设计模式，其中Model代表模型，View代表视图，Controller代表控制器。该模式采用一种业务逻辑、数据和界面分离的方式组织代码。视图与控制器的职责一目了然，然而，视图和控制器之间，以及控制器和数据库间如何解耦，则需要用到模型。</p>
<p>控制器的主要工作是访问MongoDB数据库，完成业务逻辑编写工作，然后将处理结果返回浏览器。所以核心的数据存取工作在MongoDB，即经典三层架构里的数据访问层中完成。</p>
<p>模型又分为领域模型和视图模型，控制器与数据库之间的是领域模型，视图与控制器之间的是视图模型。</p>
<p>模型又可以分为充血模型与贫血模型，贫血模型把行为逻辑和状态分离到不同的对象中，只有状态的对象就是所谓的贫血对象。</p>
<p>下面是经典的模型目录结构：1、采用经典的MVC结构，包含models、views和controllers这三个目录；2、包含routes目录，这是因为Express和Koa框架的路由都是独立的，习惯使用这种写法；3、包含services目录，这一点参考Java目录，表示在控制器层和模型层之间增加了Service。DAO：Data Access Object层。</p>
<p><img src="/../../image/%E6%95%B0%E6%8D%AE%E5%BA%93/node.png" alt="node"></p>
<h1 id="MongoDB"><a href="#MongoDB" class="headerlink" title="MongoDB"></a>MongoDB</h1><p>MongoDB的安装和部署方式主要有以下两种：</p>
<p>1、采用复制集：复制集通常由三个对等的结点构成，有primary和secondary等多种角色；primary负责读、写请求，secondary负责读请求，secondary紧跟primary并应用写操作。如果primary失效，则集群进行多数派选举，选举出新得primary。复制集是MongoDB垂直扩展的最小部署单位，解决了单点故障问题。分片集群中每个shard节点也可以使用复制集提高数据的可用性。但复制集也有缺点，主要在于集群数据的容量受限于单个节点的磁盘大小，如果数据量不断增加，对数据库进行扩容将是非常痛苦的事情。</p>
<p>2、采用分片集群：分片模式将整个集合中的数据根据分片键分别存储到多个MongoDB节点上，即让每一个节点持有集合的一部分数据，集群持有全部数据。这种分片方式，应对高并发、超大数据量的场景时，效果良好：</p>
<h2 id="Mongoose"><a href="#Mongoose" class="headerlink" title="Mongoose"></a>Mongoose</h2><p>MongoDB是一个开源的非关系型数据库，适合在数据规模大、事务性不强的场景下使用，同时它也是一个对象数据库，其中没有表、行等概念，也没有固定的模式和结构，所有的数据以文档的形式存储。所谓文档，就是一个关联数组式的对象，由属性组成，一个属性对应的值可能式一个数、字符串、日期、数组，甚至是一个嵌套的文档。数据格式为类似JSON的BSON格式。</p>
<p>Mongoose是MongoDB的一个对象模型工具，基于Node-MongoDB-Native开发的MongoDB的Node.js驱动，可在Node.js的异步环境下执行。可以把Mongoose理解为简易版的ORM（对象关系映射）。Mongoose提供了类似Schema表结构的定义，以及Hook、PLugin、Virtual、Populate等机制。</p>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/23/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/less%E4%B8%8Esass/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/23/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/less%E4%B8%8Esass/" class="post-title-link" itemprop="url">less与sass</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-23 21:28:16" itemprop="dateCreated datePublished" datetime="2021-09-23T21:28:16+08:00">2021-09-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:33:08" itemprop="dateModified" datetime="2021-11-03T16:33:08+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/" itemprop="url" rel="index"><span itemprop="name">学校项目应用</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>最近接手别人的项目后，后面新迭代的需求需要使用less与sass来实现样式，在vue的main.js中引入样式后，发现与less相关的解析依赖并没有配置。安装完less与less-loader之后，配置好了less的处理方案，但后续一直会有奇怪的报错。</p>
<p>踩了好几个坑之后终于成功配置好了，具体的问题有以下两个：</p>
<p>1、如果在处理less时，出现多个解析重复导致问题，一般是因为该版本在build/utils中已经配置了less的处理，而这样就会与build/webpack.conf.js中配置的less-loader起冲突，我们只要删掉一个解析就可以了。</p>
<p>2、由于是中途接手的项目，不太熟悉，之前的我的vue项目都是用vue-cli3.0构建的，而万万没想到，这个项目还是用的2.0脚手架。而vue-cli2.0与3.0对less的配置是不一样的。这里，在报错：Inline JavaScript is not enabled. Is it set in your options?后。如果是vue-cli2.0的版本，则是在build/utils中</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> &#123;</span><br><span class="line">    css: generateLoaders(),</span><br><span class="line">    postcss: generateLoaders(),</span><br><span class="line">    less: generateLoaders(<span class="string">'less'</span>,&#123;<span class="attr">javascriptEnabled</span>: <span class="literal">true</span>&#125;),</span><br><span class="line">    <span class="comment">//对于less添加上javascriptEnabled: true</span></span><br><span class="line">    sass: generateLoaders(<span class="string">'sass'</span>, &#123; <span class="attr">indentedSyntax</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    scss: generateLoaders(<span class="string">'sass'</span>, ),</span><br><span class="line">    stylus: generateLoaders(<span class="string">'stylus'</span>),</span><br><span class="line">    styl: generateLoaders(<span class="string">'stylus'</span>)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>如果是vue-cli3.0的版本，则在vue.config.js中添加</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line"></span><br><span class="line">    css: &#123;</span><br><span class="line"></span><br><span class="line">        loaderOptions: &#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 向 CSS 相关的 loader 传递选项</span></span><br><span class="line"></span><br><span class="line">           less: &#123;</span><br><span class="line">               javascriptEnabled: <span class="literal">true</span></span><br><span class="line">           &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/23/webgl/three.js%E5%87%A0%E4%BD%95%E4%BD%93/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/23/webgl/three.js%E5%87%A0%E4%BD%95%E4%BD%93/" class="post-title-link" itemprop="url">three.js几何体</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-23 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-23T12:18:39+08:00">2021-09-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:22:08" itemprop="dateModified" datetime="2021-11-03T16:22:08+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webgl/" itemprop="url" rel="index"><span itemprop="name">webgl</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><p>Three.js中有用于代表几何体的两个可用基类：THREE.Geometry与THREE.BufferGeometry。前者是旧版本中几何体的基类，后者则由新版本提供给开发者，新基类的内部数据结构组织与GPU所期待的数据结构保持一致，从而提高了运行效率。</p>
<p>Geometry用vertices顶点、faces面来定义物体形状，分别定义物体的顶点数组与面数组。</p>
<p>BufferGeometry用attributes分量、index索引来定义物体形状，attributes分量所存储的信息将直接送往GPU进行处理。index索引，一般不需要特意指定面，因为默认情况下position位置分量中每三个空间坐标确定一个面。但我们也可以通过index属性像Geometry类一样去指定用于组成每一个面的顶点。</p>
<h1 id="基础几何体"><a href="#基础几何体" class="headerlink" title="基础几何体"></a>基础几何体</h1><h2 id="二维几何体"><a href="#二维几何体" class="headerlink" title="二维几何体"></a>二维几何体</h2><p>THREE.PlaneGeometry</p>
<p>PlaneGeometry对象可以用来创建一个非常简单的二维矩形，有以下四种基本的属性：width（宽度）、height（高度）、widthSegments（宽度段数，指定矩形宽度应该分为几段）、heightSegments（高度段数，指定矩形宽度应该分为几段）。</p>
<p>THREE.CircleGeometry</p>
<p>PlaneGeometry对象可以用来创建一个非常简单的二维圆或者部分圆。</p>
<p>THREE.RingGeometry</p>
<p>RingGeometry对象不仅可以创建一个圆，还可以在中心定义一个孔。</p>
<p>THREE.ShapeGeometry</p>
<p>ShapeGeometry用于创建一个自定义的二维图形，通过该几何体，我们可以调用几个函数来创建自己的图形，</p>
<h2 id="三维几何体"><a href="#三维几何体" class="headerlink" title="三维几何体"></a>三维几何体</h2><p>THREE.BoxGeometry</p>
<p>简单的长方体几何体。</p>
<p>THREE.SphereGeometry</p>
<p>简单的三维球体。</p>
<p>THREE.CylinderGeometry</p>
<p>用于创建三维圆柱体。</p>
<p>THREE.ConeGeometry</p>
<p>用于创建三维圆锥体。</p>
<p>THREE.TorusGeometry</p>
<p>用于创建三维的中空环状物体，类似于甜甜圈。</p>
<p>THREE.TorusKnotGeometry</p>
<p>用于创建三维的环状扭结，类似于九连环之类的环状物体。</p>
<p>THREE.PolyhedronGeometry</p>
<p>使用该集合体，能够轻松地创建多面体，十六面或者六十面体。</p>
<h2 id="高级几何体"><a href="#高级几何体" class="headerlink" title="高级几何体"></a>高级几何体</h2><p>之前展示的基本都是three.js提供的基础几何体。这一部分主要涉足THREE.js库提供的高级几何体。</p>
<p>THREE.ConvexGeometry</p>
<p>通过THREE.ConvexGeometry，我们可以围绕一组点创建一个凸包。所谓凸包就是包围这组点的最小图形。THREE.ConvexGeometry的构造函数接受一个顶点数组作为唯一参数，同时，我们需要调用computeVertexNormals和computeFaceNormals两个函数来计算法线，因为顶点和面的法线是Three.js为物体渲染平滑的表面所必需的数据，该类需要我们主动去调用函数去执行该运算。</p>
<p>THREE.LathGeometry</p>
<p>THREE.LathGeometry允许你从一条光滑曲线创建图形，该曲线由多个点来定义，通常称作样条曲线。该样条曲线绕物体的中心Z轴旋转，得到类似花瓶或者铃铛的图形</p>
<h3 id="拉伸二维图形"><a href="#拉伸二维图形" class="headerlink" title="拉伸二维图形"></a>拉伸二维图形</h3><p>THREE.ExtrudeGeometry</p>
<p>通过THREE.ExtrudeGeometry，我们可以从一个二维图形创建一个三维图形，具体的方式是沿Z轴或者其他坐标拉伸，最终形成一个三维图形。</p>
<p>同理，除了用自己的二维图形拉伸为三维图形以外，其实SVG与创建图形的方式基本相同，因此其实可以从SVG拉伸出三维图形。SVG的含义是可缩放矢量图，基于XML标准，用于在网页上创建二维矢量图。使用d3-threeD库，我们可以自动转换这些SVG指令。</p>
<p>THREE.TubeGeometry</p>
<p>THREE.TubeGeometry沿着一条三维的样条曲线拉伸出一根管，我们可以指定一些顶点来定义路径，然后用THREE.TubeGeometry来创建这根管。</p>
<p>THREE.ParametricGeometry</p>
<p>通过THREE.ParametricGeometry，你可以创建基于等式的几何体，利用几个函数公式来创建几何体。最常见的是用于创建波浪平面的函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> radialWave = <span class="function"><span class="keyword">function</span> (<span class="params">u, v, optionalTarget</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> result = optionalTarget || <span class="keyword">new</span> THREE.Vector3();</span><br><span class="line">    <span class="keyword">var</span> r = <span class="number">50</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> x = <span class="built_in">Math</span>.sin(u) * r;</span><br><span class="line">    <span class="keyword">var</span> z = <span class="built_in">Math</span>.sin(v / <span class="number">2</span>) * <span class="number">2</span> * r;</span><br><span class="line">    <span class="keyword">var</span> y = (<span class="built_in">Math</span>.sin(u * <span class="number">4</span> * <span class="built_in">Math</span>.PI) + <span class="built_in">Math</span>.cos(v * <span class="number">2</span> * <span class="built_in">Math</span>.PI)) * <span class="number">2.8</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result.set( x, y, z );</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>

<p>正如上述的代码，只需要几行，我们就可以创建出非常有趣的几何体</p>
<h3 id="三维文本"><a href="#三维文本" class="headerlink" title="三维文本"></a>三维文本</h3><p>在Three.js中渲染文本非常容易，你所需要做的只是指定想要用的字体，以及我们在讨论THREE.ExtrudeGeometry时见到过的基本拉伸属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">init</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// use the defaults</span></span><br><span class="line">  <span class="keyword">var</span> stats = initStats();</span><br><span class="line">  <span class="keyword">var</span> renderer = initRenderer();</span><br><span class="line">  <span class="keyword">var</span> camera = initCamera();</span><br><span class="line">  <span class="keyword">var</span> scene = <span class="keyword">new</span> THREE.Scene();</span><br><span class="line">  initDefaultLighting(scene);</span><br><span class="line">  <span class="keyword">var</span> groundPlane = addLargeGroundPlane(scene)</span><br><span class="line">  groundPlane.position.y = <span class="number">-30</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> font_bitstream;</span><br><span class="line">  <span class="keyword">var</span> font_helvetiker_bold;</span><br><span class="line">  <span class="keyword">var</span> font_helvetiker_regular;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> step = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">var</span> text1;</span><br><span class="line">  <span class="keyword">var</span> text2;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> fontload1 = <span class="keyword">new</span> THREE.FontLoader();</span><br><span class="line">  fontload1.load( <span class="string">'../../assets/fonts/bitstream_vera_sans_mono_roman.typeface.json'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"> response </span>) </span>&#123;</span><br><span class="line">    controls.font = response;</span><br><span class="line">    font_bitstream = response;</span><br><span class="line">    controls.redraw();</span><br><span class="line">    render();</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> fontload2 = <span class="keyword">new</span> THREE.FontLoader();</span><br><span class="line">  fontload2.load( <span class="string">'../../assets/fonts/helvetiker_bold.typeface.json'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"> response </span>) </span>&#123;</span><br><span class="line">    font_helvetiker_bold = response;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> fontload3 = <span class="keyword">new</span> THREE.FontLoader();</span><br><span class="line">  fontload3.load( <span class="string">'../../assets/fonts/helvetiker_regular.typeface.json'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"> response </span>) </span>&#123;</span><br><span class="line">    font_helvetiker_regular = response;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> controls = <span class="keyword">new</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.appliedMaterial = applyMeshNormalMaterial</span><br><span class="line">    <span class="keyword">this</span>.castShadow = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">this</span>.groundPlaneVisible = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.size = <span class="number">90</span>;</span><br><span class="line">    <span class="keyword">this</span>.height = <span class="number">90</span>;</span><br><span class="line">    <span class="keyword">this</span>.bevelThickness = <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">this</span>.bevelSize = <span class="number">0.5</span>;</span><br><span class="line">    <span class="keyword">this</span>.bevelEnabled = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">this</span>.bevelSegments = <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">this</span>.bevelEnabled = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">this</span>.curveSegments = <span class="number">12</span>;</span><br><span class="line">    <span class="keyword">this</span>.steps = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">this</span>.fontName = <span class="string">"bitstream vera sans mono"</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// redraw function, updates the control UI and recreates the geometry.</span></span><br><span class="line">    <span class="keyword">this</span>.redraw = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">switch</span> (controls.fontName) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'bitstream vera sans mono'</span>: </span><br><span class="line">          controls.font = font_bitstream</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'helvetiker'</span>: </span><br><span class="line">          controls.font = font_helvetiker_regular</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'helvetiker bold'</span>: </span><br><span class="line">          controls.font = font_helvetiker_bold</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      redrawGeometryAndUpdateUI(gui, scene, controls, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> options = &#123;</span><br><span class="line">              size: controls.size,</span><br><span class="line">              height: controls.height,</span><br><span class="line">              weight: controls.weight,</span><br><span class="line">              font: controls.font,</span><br><span class="line">              bevelThickness: controls.bevelThickness,</span><br><span class="line">              bevelSize: controls.bevelSize,</span><br><span class="line">              bevelSegments: controls.bevelSegments,</span><br><span class="line">              bevelEnabled: controls.bevelEnabled,</span><br><span class="line">              curveSegments: controls.curveSegments,</span><br><span class="line">              steps: controls.steps</span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> geom = <span class="keyword">new</span> THREE.TextGeometry(<span class="string">"Learning Three.js"</span>, options)</span><br><span class="line">            geom.applyMatrix(<span class="keyword">new</span> THREE.Matrix4().makeScale(<span class="number">0.05</span>,<span class="number">0.05</span>,<span class="number">0.05</span>));</span><br><span class="line">            geom.center();</span><br><span class="line">    </span><br><span class="line">            <span class="keyword">return</span> geom</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;;</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> gui = <span class="keyword">new</span> dat.GUI();</span><br><span class="line">  gui.add(controls, <span class="string">'size'</span>, <span class="number">0</span>, <span class="number">200</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'height'</span>, <span class="number">0</span>, <span class="number">200</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'fontName'</span>, [<span class="string">'bitstream vera sans mono'</span>, <span class="string">'helvetiker'</span>, <span class="string">'helvetiker bold'</span>]).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'bevelThickness'</span>, <span class="number">0</span>, <span class="number">10</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'bevelSize'</span>, <span class="number">0</span>, <span class="number">10</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'bevelSegments'</span>, <span class="number">0</span>, <span class="number">30</span>).step(<span class="number">1</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'bevelEnabled'</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'curveSegments'</span>, <span class="number">1</span>, <span class="number">30</span>).step(<span class="number">1</span>).onChange(controls.redraw);</span><br><span class="line">  gui.add(controls, <span class="string">'steps'</span>, <span class="number">1</span>, <span class="number">5</span>).step(<span class="number">1</span>).onChange(controls.redraw);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// add a material section, so we can switch between materials</span></span><br><span class="line">    gui.add(controls, <span class="string">'appliedMaterial'</span>, &#123;</span><br><span class="line">      meshNormal: applyMeshNormalMaterial, </span><br><span class="line">      meshStandard: applyMeshStandardMaterial</span><br><span class="line">    &#125;).onChange(controls.redraw)</span><br><span class="line">    </span><br><span class="line">    gui.add(controls, <span class="string">'castShadow'</span>).onChange(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;controls.mesh.castShadow = e&#125;)</span><br><span class="line">    gui.add(controls, <span class="string">'groundPlaneVisible'</span>).onChange(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;groundPlane.material.visible = e&#125;)</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">render</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    stats.update();</span><br><span class="line"></span><br><span class="line">    controls.mesh.rotation.y = step+=<span class="number">0.005</span></span><br><span class="line">    controls.mesh.rotation.x = step</span><br><span class="line">    controls.mesh.rotation.z = step</span><br><span class="line"></span><br><span class="line">    <span class="comment">// render using requestAnimationFrame</span></span><br><span class="line">    requestAnimationFrame(render);</span><br><span class="line">    renderer.render(scene, camera);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码首先利用Three.js提供的THREE.FondLoader类加载字体，在调用THREE.FondLoader.load()方法时，我们除了提供字体名称以外，还提供了一个临时回调函数，用于接收创建好的字体对象（即上面代码的response对象），然后将字体对象保存到变量loadedFont中，并调用render()函数来重新绘制场景，接着我们将接收到的字体对象包含在一个名为options的映射表变量中，并用它来创建THREE.TextGeometry几何体对象</p>
<h3 id="二元操作组合"><a href="#二元操作组合" class="headerlink" title="二元操作组合"></a>二元操作组合</h3><p>之前我们其实一直是利用Three.js提供的几何体进行各种操作变化，其实所能做的也会受限于THREE.js库，其实我们可以利用CSG（构造实体几何体）的技术，来将各种标准几何体组合在一起成为新的几何体。</p>
<p>intersect（相交）：使用该函数可以基于两个现有几何体的交集创建出新的几何体，两个几何体的重叠部分定义此新几何体的形状；</p>
<p>union(联合)：使用该函数可以将两个几何体联合起来创建出一个新的几何体；</p>
<p>subtract(相减)：与union相反，通过该函数，可以在第一个几何体中，移除两个几何体重叠的部分，来创建新的几何体。</p>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/16/webgl/three.js%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/16/webgl/three.js%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97/" class="post-title-link" itemprop="url">three.js初学</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-16 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-16T12:18:39+08:00">2021-09-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:22:12" itemprop="dateModified" datetime="2021-11-03T16:22:12+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webgl/" itemprop="url" rel="index"><span itemprop="name">webgl</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><h2 id="初始化场景"><a href="#初始化场景" class="headerlink" title="初始化场景"></a>初始化场景</h2><p>场景scene是一个容器，主要用于保存、跟踪所要渲染得物体和所使用的光源。</p>
<p>摄像机camera决定了能在场景看到什么。</p>
<p>渲染器renderer对象会基于摄像机的角度来计算场景对象在浏览器会渲染册灰姑娘什么样子。</p>
<p>轴与平面axes、plane。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">init</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// create a scene, that will hold all our elements such as objects, cameras and lights.</span></span><br><span class="line">    <span class="keyword">var</span> scene = <span class="keyword">new</span> THREE.Scene();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create a camera, which defines where we're looking at.</span></span><br><span class="line">    <span class="keyword">var</span> camera = <span class="keyword">new</span> THREE.PerspectiveCamera(<span class="number">45</span>, <span class="built_in">window</span>.innerWidth / <span class="built_in">window</span>.innerHeight, <span class="number">0.1</span>, <span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create a render and set the size</span></span><br><span class="line">    <span class="keyword">var</span> renderer = <span class="keyword">new</span> THREE.WebGLRenderer();</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    最初定义最需要的三要素：场景、摄像机、渲染器；</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    renderer.setClearColor(<span class="keyword">new</span> THREE.Color(<span class="number">0x000000</span>));</span><br><span class="line">    <span class="comment">//设置背景颜色与场景大小</span></span><br><span class="line">    renderer.setSize(<span class="built_in">window</span>.innerWidth, <span class="built_in">window</span>.innerHeight);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// show axes in the screen</span></span><br><span class="line">    <span class="comment">//定义并添加坐标轴与平面，在three.js中，我们通过创建材质对象来设置平面的外观。</span></span><br><span class="line">    <span class="keyword">var</span> axes = <span class="keyword">new</span> THREE.AxesHelper(<span class="number">20</span>);</span><br><span class="line">    scene.add(axes);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create the ground plane</span></span><br><span class="line">    <span class="keyword">var</span> planeGeometry = <span class="keyword">new</span> THREE.PlaneGeometry(<span class="number">60</span>, <span class="number">20</span>);</span><br><span class="line">    <span class="keyword">var</span> planeMaterial = <span class="keyword">new</span> THREE.MeshBasicMaterial(&#123;</span><br><span class="line">        color: <span class="number">0xAAAAAA</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">var</span> plane = <span class="keyword">new</span> THREE.Mesh(planeGeometry, planeMaterial);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// rotate and position the plane</span></span><br><span class="line">    plane.rotation.x = <span class="number">-0.5</span> * <span class="built_in">Math</span>.PI;</span><br><span class="line">    plane.position.set(<span class="number">15</span>, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// add the plane to the scene</span></span><br><span class="line">    scene.add(plane);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create a cube</span></span><br><span class="line">    <span class="keyword">var</span> cubeGeometry = <span class="keyword">new</span> THREE.BoxGeometry(<span class="number">4</span>, <span class="number">4</span>, <span class="number">4</span>);</span><br><span class="line">    <span class="keyword">var</span> cubeMaterial = <span class="keyword">new</span> THREE.MeshBasicMaterial(&#123;</span><br><span class="line">        color: <span class="number">0xFF0000</span>,</span><br><span class="line">        wireframe: <span class="literal">true</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">var</span> cube = <span class="keyword">new</span> THREE.Mesh(cubeGeometry, cubeMaterial);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// position the cube</span></span><br><span class="line">    cube.position.set(<span class="number">-4</span>, <span class="number">3</span>, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// add the cube to the scene</span></span><br><span class="line">    scene.add(cube);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// create a sphere</span></span><br><span class="line">    <span class="keyword">var</span> sphereGeometry = <span class="keyword">new</span> THREE.SphereGeometry(<span class="number">4</span>, <span class="number">20</span>, <span class="number">20</span>);</span><br><span class="line">    <span class="keyword">var</span> sphereMaterial = <span class="keyword">new</span> THREE.MeshBasicMaterial(&#123;</span><br><span class="line">        color: <span class="number">0x7777FF</span>,</span><br><span class="line">        wireframe: <span class="literal">true</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">var</span> sphere = <span class="keyword">new</span> THREE.Mesh(sphereGeometry, sphereMaterial);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// position the sphere</span></span><br><span class="line">    sphere.position.set(<span class="number">20</span>, <span class="number">4</span>, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// add the sphere to the scene</span></span><br><span class="line">    scene.add(sphere);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// position and point the camera to the center of the scene</span></span><br><span class="line">    <span class="comment">//设置摄像机的位置与其观察的方位</span></span><br><span class="line">    camera.position.set(<span class="number">-30</span>, <span class="number">40</span>, <span class="number">30</span>);</span><br><span class="line">    camera.lookAt(scene.position);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// add the output of the renderer to the html element</span></span><br><span class="line">    <span class="built_in">document</span>.getElementById(<span class="string">"webgl-output"</span>).appendChild(renderer.domElement);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// render the scene</span></span><br><span class="line">    renderer.render(scene, camera);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="材质、光源与阴影"><a href="#材质、光源与阴影" class="headerlink" title="材质、光源与阴影"></a>材质、光源与阴影</h2><p>光源spotLight定义光源位置，并从其位置照射场景；通过将castShadow属性设置为true，three.js的阴影功能被启用。</p>
<p>材质Material用来定义物体的颜色以及视觉效果程度，有的材质也会对光源产生反应。</p>
<p>渲染阴影需要消耗大量性能，因此three.js默认不会渲染阴影，首先需要设置shdowMapEnabled属性为true，然后需要明确指定哪个物体投射阴影，哪个物体接受阴影，相应的receiveShadow、castShadow属性设置为true。同时，我们需要定义能够产生阴影的光源，通过spotlight.castshadow属性来设置。</p>
<h2 id="动画"><a href="#动画" class="headerlink" title="动画"></a>动画</h2><p>动画实现的关键是：如何在特定的事件间隔重新渲染场景。在H5相关的API出现之前，是通过setInterval方法来实现的，但该方法并没有与屏幕的刷新同步，将导致高的CPU使用率与性能不良。</p>
<h3 id="requestAnimationFrame"><a href="#requestAnimationFrame" class="headerlink" title="requestAnimationFrame"></a>requestAnimationFrame</h3><p> requestAnimationFrame该函数为稳定而连续的渲染场景提供了良好的解决方案；通过该函数，你可以向浏览器提供一个回调函数，无须定义回调间隔，浏览器会自行决定最佳的回调时机。</p>
<p>你需要做的是在这个回调函数里完成一帧绘制操作，将剩下工作交给浏览器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">init</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="built_in">document</span>.getElementById(<span class="string">"webgl-output"</span>).appendChild(renderer.domElement);</span><br><span class="line">    <span class="comment">//在场景创建完成后，不再调用renderer.render()方法，而是调用renderScene()来启动动画</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// call the render function</span></span><br><span class="line">    <span class="keyword">var</span> step = <span class="number">0</span>;</span><br><span class="line">    renderScene();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">renderScene</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        stats.update();</span><br><span class="line">        <span class="comment">// rotate the cube around its axes</span></span><br><span class="line">        cube.rotation.x += <span class="number">0.02</span>;</span><br><span class="line">        cube.rotation.y += <span class="number">0.02</span>;</span><br><span class="line">        cube.rotation.z += <span class="number">0.02</span>;</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        这里我们每次调用renderScene()时让物体每个方向的rotation属性+0.02</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        <span class="comment">// bounce the sphere up and down</span></span><br><span class="line">        step += <span class="number">0.04</span>;</span><br><span class="line">        sphere.position.x = <span class="number">20</span> + (<span class="number">10</span> * (<span class="built_in">Math</span>.cos(step)));</span><br><span class="line">        sphere.position.y = <span class="number">2</span> + (<span class="number">10</span> * <span class="built_in">Math</span>.abs(<span class="built_in">Math</span>.sin(step)));</span><br><span class="line">        <span class="comment">// render using requestAnimationFrame</span></span><br><span class="line">        requestAnimationFrame(renderScene);</span><br><span class="line">        <span class="comment">//这里我们将递归执行其本身，从而让动画一直执行</span></span><br><span class="line">        renderer.render(scene, camera);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于动画的监控，我们可以使用Stats.js来实时监测帧数；使用dat.GUI简化实验流程。</p>
<h1 id="基本组件"><a href="#基本组件" class="headerlink" title="基本组件"></a>基本组件</h1><h2 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h2><p>一个场景想要显示任何东西，需要最少有以下的组件：摄像机（决定屏幕上哪些东西需要渲染）、光源（决定材质如何显示以及用于产生阴影）、对象（摄像机透视图里主要渲染对象）、渲染器（基于摄像机和场景提供的信息，调用底层API执行真正的场景绘制工作）。</p>
<p>THREE.Scene:环境；THREE.Mesh：平面；</p>
<p>THREE.SpotLight：聚光灯光源；THREE.AmbientLight：环境光；</p>
<p>THREE.Camera：摄像机；</p>
<p>场景相关方法有：</p>
<p>THREE.Scene.Add：用于向场景中添加对象；THREE.Scene.Remove：用于移除场景中的对象；</p>
<p>THREE.Scene.children：用于获取场景中所有的子对象列表；THREE.Scene.getObjectByName：利用name属性，用于获取场景中特定的对象.</p>
<p>THREE.Scene.traverse()：该方法可以将一个方法作为参数传入函数，这个传递来的方法会在每一个子对象上执行。由于Scene存储的是对象树，因此相当于递归遍历树，会在所有子对象上执行，直至遍历完场景中的所有对象为止。</p>
<p>雾化效果：THREE.Scene.fog属性，使得场景中的物体离摄像机越远就会变得越模糊；此时雾化效果是线性增强的。THREE.Scene.FogExp2属性：此时雾化效果是随距离呈指数增长的。</p>
<p>THREE.Scene.overrideMaterial属性：当设置该属性后，场景中所有物体都会使用该属性指向的材质。</p>
<h2 id="物体"><a href="#物体" class="headerlink" title="物体"></a>物体</h2><p>几何体：THREE.Geometry。</p>
<p>当我们使用Three.js提供的几何体时，不需要自己定义顶点与面，只要定义长宽高就可由引擎正确创建，当然，也可以调用Geometry.vertices定义顶点，Geometry.Faces定义面。</p>
<p>clone方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.clone = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">          <span class="keyword">var</span> clonedGeometry = mesh.children[<span class="number">0</span>].geometry.clone();</span><br><span class="line">          <span class="keyword">var</span> materials = [</span><br><span class="line">              <span class="keyword">new</span> THREE.MeshLambertMaterial(&#123;<span class="attr">opacity</span>: <span class="number">0.8</span>, <span class="attr">color</span>: <span class="number">0xff44ff</span>, <span class="attr">transparent</span>: <span class="literal">true</span>&#125;),</span><br><span class="line">              <span class="keyword">new</span> THREE.MeshBasicMaterial(&#123;<span class="attr">color</span>: <span class="number">0x000000</span>, <span class="attr">wireframe</span>: <span class="literal">true</span>&#125;)</span><br><span class="line">          ];</span><br><span class="line"></span><br><span class="line">          <span class="keyword">var</span> mesh2 = THREE.SceneUtils.createMultiMaterialObject(clonedGeometry, materials);</span><br><span class="line">    	<span class="comment">//利用createMultiMaterialObject方法将多个材质合成后，生成克隆后的对象。</span></span><br><span class="line">          mesh2.children.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">              e.castShadow = <span class="literal">true</span></span><br><span class="line">          &#125;);</span><br><span class="line">    	<span class="comment">//为该组中所有子对象添加阴影</span></span><br><span class="line">          mesh2.translateX(<span class="number">5</span>);</span><br><span class="line">          mesh2.translateZ(<span class="number">5</span>);</span><br><span class="line">          mesh2.name = <span class="string">"clone"</span>;</span><br><span class="line">          scene.remove(scene.getChildByName(<span class="string">"clone"</span>));</span><br><span class="line">          scene.add(mesh2);</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>

<p>网格物体对象的常见属性值：</p>
<p>position:该属性决定对象相对于父对象的位置，通常父对象为THREE.Scene对象或THREE.Object3D。</p>
<p>rotation:该属性可以设置绕每个轴的旋转弧度，其有rotateX、rotateY、rotateZ来设置相对特定轴的旋转弧度。在数学上旋转一周的弧度制为2Π。 </p>
<p>scale:通过该属性可沿着x、y、z轴来缩放对象。</p>
<p>visible：该属性设置为false时，不会渲染至场景中。</p>
<h2 id="摄像机"><a href="#摄像机" class="headerlink" title="摄像机"></a>摄像机</h2><p>透视投影摄像机：生成透视视图，离摄像机越远的物体，其渲染的尺寸就越小。THREE.PerspectiveCamera</p>
<p>正交投影摄像机：所有立方体被渲染出的尺寸都是一样的，对象相对于摄像机的距离对渲染的结果没有影响。THREE.OrthographicCamera。</p>
<p>透视投影摄像机的结果更贴近于真实世界。</p>
<p>THREE.PerspectiveCamera：透视投影摄像机的属性如下：使用透视摄像机时相当于是从一点发出的摄像视窗。</p>
<p>fov：表示视场，这是摄像机啊中能看到的那部分场景；人类的视场为180。</p>
<p>aspect：长宽比，这是渲染结果的横向尺寸和纵向尺寸的比值，由于一般使用窗口作为输出界面，因此使用的是窗口长宽比。</p>
<p>near：近面面积，从距离摄像机多近的距离则开始渲染；</p>
<p>far：远面面积，定义了摄像机从它所处的位置能够看多远。设的较小则有部分场景不被渲染，设的较大则会影响渲染性能。</p>
<p>zoom：变焦，使用该属性可放大、缩小场景。</p>
<p>THREE.OrthographicCamera：正交投影摄像机，相当于是从一个面平行发出的摄像视窗。</p>
<p>left、right、top、bottom:可视渲染范围的边界设置。</p>
<p>near、far：近面、远面面积。</p>
<p>zoom：变焦。</p>
<p>Camera.lookat()方法可以让摄像机指向某一点，或者传入某物体的position，则可让摄像机追随该物体。</p>
<h1 id="光源"><a href="#光源" class="headerlink" title="光源"></a>光源</h1><p>webGL本身并不支持光源，如果不使用three.js则需要自己写WebGL着色器程序。</p>
<p>Three.js中光源很多，每一种都有不同的用法</p>
<h2 id="基础光源"><a href="#基础光源" class="headerlink" title="基础光源"></a>基础光源</h2><h3 id="基本光源"><a href="#基本光源" class="headerlink" title="基本光源"></a>基本光源</h3><p>THREE.AmbientLight：基本光源，其颜色会应用到全局，且不会生成阴影；会将场景中物体均渲染为相同颜色。</p>
<p>THREE.Color对象：在为材质、灯光指定颜色时，可以使用字符串或者用THREE.Color对象，此时可通过直接修改THREE.Color类携带的方法来读取和修改内部颜色值。</p>
<h3 id="聚光灯光源"><a href="#聚光灯光源" class="headerlink" title="聚光灯光源"></a>聚光灯光源</h3><p>THREE.SpotLight:聚光灯光源，是最常用的光源之一，是一种具有锥形效果的光源，可与手电筒、灯塔的光相对比，其光具有方向与角度。其常用属性如下：</p>
<p>angle:角度，光源发射出的光束的宽度。castShadow：投影，设置为true时，该光源会产生阴影。</p>
<p>color：光源的颜色。decay：衰减，光源强度随着离开光源的距离而衰减的速度。</p>
<p>distance：光源照射的距离。intensity：光源照射的强度。</p>
<p>position：光源所在的位置。penumbra：半影区，该属性设置聚光灯的追星照明区域在其边缘附近的平滑衰减速度。</p>
<p>power：功率。target:目标。将spotlight光源指向场景中的特定对象或位置。visible：光源开关。</p>
<p>当光源的shadow属性设置为enable时，可通过下面属性来调整阴影的特性。</p>
<p>shadow.bias：阴影偏移，用于设置阴影的位置；shadow.camera.far：投影远点，设置到距离光源的哪一个位置可以生成阴影。</p>
<p>shadow.camera.fov：投影视场，用于生成阴影的视场大小。shdow.camera.near：投影近点。</p>
<p>shadow.mapSize.width和shadow.mapSize.height：阴影映射面积与映射高度。shadow.radius：半径。</p>
<h3 id="点光源"><a href="#点光源" class="headerlink" title="点光源"></a>点光源</h3><p>THREE.PointLight：点光源，是一种单点发光、照射所有方向的光源。其常用的属性如下：</p>
<p>color:颜色；distance：距离；intensity：光源照射的强度；position：位置。</p>
<p>visible：是否可见；decay：衰减。光源强度随着离开光源的距离而衰减的速度。power：功率。</p>
<p>同样，点光源可以像聚光灯光源一样启用阴影并设置其属性。THREE.PointLight同样使用摄像机来决定如何绘制阴影，所以也可以使用辅助类THREE.CameraHelper来展示场景中哪些部分被光源的摄像机所覆盖；使用THREE.PointLightHelper来展示点光源的光线所照射的位置。</p>
<h3 id="平行光源"><a href="#平行光源" class="headerlink" title="平行光源"></a>平行光源</h3><p>THREE.DirectionalLight：平行光，该类型可以看作是距离很远的光，它发出的光线都是相互平行的。且平行光不像聚光灯那样离目标越远越暗淡，被平行光照亮的区域接受到的光强是一样的。且由于所有的光线是平行的，所以不会有光锥，而是一个立方体区域。</p>
<h2 id="特殊光源"><a href="#特殊光源" class="headerlink" title="特殊光源"></a>特殊光源</h2><h3 id="半球光光源"><a href="#半球光光源" class="headerlink" title="半球光光源"></a>半球光光源</h3><p>THREE.HemisphereLight：半球光光源可以模拟出更自然的户外光照效果，考虑了天空和地面的折射。</p>
<h3 id="区域光光源"><a href="#区域光光源" class="headerlink" title="区域光光源"></a>区域光光源</h3><p>THREE.AreaLight：可定义一个长方形的发光区域。</p>
<h3 id="镜头光晕"><a href="#镜头光晕" class="headerlink" title="镜头光晕"></a>镜头光晕</h3><p>通过实例化THREE.LensFlare对象来创建镜头光晕。该对象可以接受以下参数：</p>
<p>texture：纹理；size：尺寸；distance：距离；blending：混合；color：颜色；opacity：不透明度。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>AmbientLight基本光源的颜色可附加到场景中的每一个颜色中，通常用于柔化生硬的颜色与阴影；PointLight点光源会朝所有方向发射光线，不能用于创建阴影；SpotLight聚光灯光源类似于手电筒，有一个锥形的光束，可配置随距离增大而逐渐变弱，且可生成阴影；DirectionalLight光源，这个光源相当于远光的效果，其光强不会改变。类似于太阳光；</p>
<p>THREE.HemisphereLight：半球光光源可以模拟出更自然的户外光照效果，考虑了天空和地面的折射。</p>
<p>THREE.AreaLight：不从单点发射光线，而是从一个很大的区域发射光线。</p>
<h1 id="材质"><a href="#材质" class="headerlink" title="材质"></a>材质</h1><p>材质结合THREE.Geometry就可以构成THREE.Mesh对象，材质就像物体的皮肤，决定了几何体的外表。Three.js提供了一个材质基类THREE.Material，它列出了所有的共有属性。</p>
<h2 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h2><h3 id="基础属性"><a href="#基础属性" class="headerlink" title="基础属性"></a>基础属性</h3><p>id：标识符，用于识别材质，并在材质创建时赋值；uuid：生成的唯一ID。</p>
<p>name：名称。opacity：不透明度。transparent：定义是否透明，定义为true时会使用指定的opacity渲染物体。</p>
<p>overdraw：过度描绘。visible：是否可见。side：侧面，通过该属性，可定义几何体的哪一面应用材质，默认值为前面。</p>
<p>needUpdata：是否需要实时更新材质。colorWrite：是否输出颜色。</p>
<p>flatShading：平面着色，该属性控制物体表面法线的生成方式，从而影响光照效果。</p>
<p>lights：控制物体表面是否接受光照。premultipliedAlpha：该属性控制半透明表面的颜色混合方式。</p>
<p>dithering：抖动，控制是否启用颜色抖动模式。shadowSide：投影面，控制物体的哪个面投射阴影。</p>
<p>vertexColors：顶点颜色。你可为物体的每一个顶点指定特有的颜色。fog：雾，控制材质是否收到雾的影响。</p>
<h3 id="融合属性"><a href="#融合属性" class="headerlink" title="融合属性"></a>融合属性</h3><p>材质有几个与融合相关的一般属性，其决定我们渲染的颜色如何与他们后面的颜色交互。</p>
<p>blending：融合，该属性决定物体上的材质如何与背景融合，默认情况下只显示材质的上层。</p>
<p>blendSrc：融合源，创建自定义的融合模式，该属性定义物体如何与背景相融合。</p>
<p>blendSrcAlpha:融合源透明度。blendDst：融合目标，定义融合时如何使用背景。</p>
<p>blendDstAlpha：融合目标透明度。blendEquation：融合公式，默认为相加。</p>
<h3 id="高级属性"><a href="#高级属性" class="headerlink" title="高级属性"></a>高级属性</h3><p>这些属性与WebGL内部如何工作相关。</p>
<p>depthTest、depthWrite、depthFunc、alphatest、precision。</p>
<h2 id="网格材质"><a href="#网格材质" class="headerlink" title="网格材质"></a>网格材质</h2><h3 id="MeshBasicMaterial"><a href="#MeshBasicMaterial" class="headerlink" title="MeshBasicMaterial"></a>MeshBasicMaterial</h3><p>MeshBasicMaterial是一种非常简单的材质，该材质不考虑场景中光照的影响，使用该材质的网格会被渲染成简单的平面多边形，而且可以显示几何体的线框。</p>
<h3 id="MeshDepthMaterial"><a href="#MeshDepthMaterial" class="headerlink" title="MeshDepthMaterial"></a>MeshDepthMaterial</h3><p>MeshDepthMaterial：使用该材质的物体，其外观不是由光照或者某个材质属性决定的，而是由物体到摄像机的距离决定的。可以将该材质与其他材质结合使用，这样就可以容易地创建出逐渐消失的效果。</p>
<p>一般MeshDepthMaterial会与另一种颜色材质相融合后使用。</p>
<h3 id="MeshNormalMaterial"><a href="#MeshNormalMaterial" class="headerlink" title="MeshNormalMaterial"></a>MeshNormalMaterial</h3><p>MeshNormalMaterial：使用该材质时，每一面的颜色是由从该面向外指的法向量计算得到的，所谓法向量是指与面垂直的向量。法向量通常用于决定光的反射，有助于将纹理映射到三维模型，并提供有关如何计算光照、阴影、表面像素着色的信息。</p>
<h2 id="高级材质"><a href="#高级材质" class="headerlink" title="高级材质"></a>高级材质</h2><p>Three.js提供了两种高级材质MeshPhongMaterial与MeshLambertMaterial，他们会对光源做出反应，并可以分别创建光亮的材质与暗淡的材质。</p>
<h3 id="MeshPhongMaterial"><a href="#MeshPhongMaterial" class="headerlink" title="MeshPhongMaterial"></a>MeshPhongMaterial</h3><p>MeshPhongMaterial用于创建暗淡1的并不光亮的表面。</p>
<p>color：材质的环境色；emissive：自发光，材质自发光的颜色，该属性虽然不会让使用它的物体变成光源，但会使物体的颜色不受其他光源的影响。</p>
<h3 id="MeshLambertMaterial"><a href="#MeshLambertMaterial" class="headerlink" title="MeshLambertMaterial"></a>MeshLambertMaterial</h3><p>一般用于创建光亮的材质。同样有color、emissive，还有specular：高光颜色，shiness：高光度。</p>
<p>还有MeshStandardtMaterial与MeshPhysicalMaterial。两者均用于反光相关功能实现。</p>
<h3 id="ShaderMaterial"><a href="#ShaderMaterial" class="headerlink" title="ShaderMaterial"></a>ShaderMaterial</h3><p>ShaderMaterial是最常用也最复杂的材质，通过它我们用自己定制的着色器，直接在WEBGL的环境下运行，着色器将屏幕中的JS网格转换为屏幕上的像素，利用这些自定义的着色器，可明确指定对象如何渲染，以及更改Three.js中默认值。</p>
<p>ShaderMaterial中最重要部分是其两个着色器：</p>
<p>顶点着色器vertexShader，会在几何体的每一个顶点上执行，可利用该着色器通过改变顶点的位置来对几何体进行变换。</p>
<p>片元着色器fragmentShader会在几何体的每一个片段上执行，会返回这个特定片段应该显示的颜色。</p>
<h2 id="线性几何体材质"><a href="#线性几何体材质" class="headerlink" title="线性几何体材质"></a>线性几何体材质</h2><p>LineBasicMaterial用于线段的基础材质</p>
<p>LineDashedMaterial可通过指定虚线和空白间隙的长度来创建出虚线效果。</p>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/15/webgl/webgl%E6%96%B0%E6%89%8B%E6%95%99%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/15/webgl/webgl%E6%96%B0%E6%89%8B%E6%95%99%E7%A8%8B/" class="post-title-link" itemprop="url">webgl编程指南初学</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-15 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-15T12:18:39+08:00">2021-09-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:22:28" itemprop="dateModified" datetime="2021-11-03T16:22:28+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webgl/" itemprop="url" rel="index"><span itemprop="name">webgl</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><h2 id="着色器"><a href="#着色器" class="headerlink" title="着色器"></a>着色器</h2><p>initshader：初始化着色器。在固定管线中，绘制点、线简单方便，而在WebGL中绘制工作则被主要分解成顶点着色器与片元着色器。</p>
<p>在启动JS程序后，绘制工作首先进入的是顶点着色器，在顶点着色器中描述顶点特性（如位置、颜色等），顶点就是三维空间的点，比如三角形的三个顶点；然后进入到片元着色器，在片元着色器中逐片元处理像素（如光照、阴影、遮挡）。最后片元传入到颜色缓冲区，进行显示。渲染过程如下：</p>
<p><img src="/../../image/webgl%E6%96%B0%E6%89%8B%E6%95%99%E7%A8%8B/image-20210917153131886.png" alt="image-20210917153131886"></p>
<p>这个过程是一个类似水流的流向过程，所以这个过程被称为渲染管线（Pipeline）。并且，这个过程是需要我们去编程控制的，比如观察者的视角变化需要在顶点着色器去调控；光线对颜色的变化需要在片元着色器去调控等；因此，这个过程就是可编程管线。通过着色器程序，三维图像渲染就更加的灵活强大。</p>
<p>渲染管线是指将数据从3D场景转换成2D图像，最终在屏幕上显示出来的总过程。它分为几个阶段：应用阶段、几何阶段和光栅阶段。后面我们会将整个过程进行完整解析与描述。</p>
<h3 id="顶点着色器"><a href="#顶点着色器" class="headerlink" title="顶点着色器"></a>顶点着色器</h3><p>顶点着色器程序是嵌入在JS中的程序，所以虽然传入的是字符串，但其实本质是着色器描述语言（GLSL:OpenGL Shading Language）。既然是语言也就有自己的函数与变量定义。main（）函数是每个着色器程序定义的入口。在main函数中，将顶点的坐标赋值给内置变量gl_Position,点的尺寸赋值给内置变量gl_PointSize。顶点着色器一般用来对模型的顶点进行矩阵变换，一般就是将模型的所有顶点乘于一个变换矩阵，使该模型位于相对于WebGL坐标系中的某个位置。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 顶点着色器程序</span></span><br><span class="line"><span class="keyword">var</span> VSHADER_SOURCE = </span><br><span class="line">  <span class="string">'void main() &#123;\n'</span> +</span><br><span class="line">  <span class="string">'  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n'</span> + <span class="comment">// Set the vertex coordinates of the point</span></span><br><span class="line">  <span class="string">'  gl_PointSize = 10.0;\n'</span> +                    <span class="comment">// Set the point size</span></span><br><span class="line">  <span class="string">'&#125;\n'</span>;</span><br></pre></td></tr></table></figure>

<p><strong>片元着色器</strong></p>
<p>得到光栅化的片段像素位置数据之后，就可以通过片段着色器为这些像素进行上色了，这是第二个可以编程的地方；我们可以对图片进行采样之后，在这里进行上色。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 片元着色器程序</span></span><br><span class="line"><span class="keyword">var</span> FSHADER_SOURCE =</span><br><span class="line">  <span class="string">'void main() &#123;\n'</span> +</span><br><span class="line">  <span class="string">'  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n'</span> + <span class="comment">// Set the point color</span></span><br><span class="line">  <span class="string">'&#125;\n'</span>;</span><br></pre></td></tr></table></figure>

<h2 id="渲染管线"><a href="#渲染管线" class="headerlink" title="渲染管线"></a>渲染管线</h2><p>上面已经说过，渲染管线其实就是一个图形渲染的流水线过程，这里我们分步骤一个个进行解析。</p>
<h3 id="1-顶点着色器"><a href="#1-顶点着色器" class="headerlink" title="1.顶点着色器"></a>1.顶点着色器</h3><p>顶点着色器一般用来对模型的顶点进行矩阵变换，一般就是将模型的所有顶点乘于一个变换矩阵，使该模型位于相对于WebGL坐标系中的某个位置。</p>
<p>顶点着色器是可编程的，使用的语言是 GLSL 来进行编写，下面我们主要说一下几种常用的属性类型：</p>
<ul>
<li>attribute变量：用户自定义变量，一般是存储顶点属性的变量；</li>
<li>uniform变量：恒值变量，一般表示每个顶点都一致的变量，比如变换矩阵、光照等；</li>
<li>varying变量：易变变量，将顶点着色器的数据传递给片段着色器时使用；</li>
<li>内置常量：WebGL 内部的常量；</li>
</ul>
<h3 id="2-图元装配"><a href="#2-图元装配" class="headerlink" title="2.图元装配"></a>2.图元装配</h3><p>这个阶段，GPU会将我们传入的顶点装配成三角形、线段或者点；装配好之后，会自动截去不在可视区域内的信息；</p>
<h3 id="3-光栅化"><a href="#3-光栅化" class="headerlink" title="3.光栅化"></a>3.光栅化</h3><p>这个阶段，GPU会将装配好的三角形转换成对应的像素，并将这些像素传入下一个阶段；</p>
<h3 id="4-片段着色器"><a href="#4-片段着色器" class="headerlink" title="4.片段着色器"></a>4.片段着色器</h3><p>得到光栅化的片段像素位置数据之后，就可以通过片段着色器为这些像素进行上色了，这是第二个可以编程的地方；</p>
<p>我们可以对图片进行采样之后，再这里进行上色；</p>
<h3 id="5-逐片段操作"><a href="#5-逐片段操作" class="headerlink" title="5.逐片段操作"></a>5.逐片段操作</h3><p>本步骤包含了多个子操作，每个操作都会影响当前片段最终的显示效果，下面我们看下几个常见的子操作：</p>
<h3 id="6、帧缓存"><a href="#6、帧缓存" class="headerlink" title="6、帧缓存"></a>6、帧缓存</h3><p>数据经过整个渲染管线处理之后，最终会写入到帧缓存中，帧缓存存储了最终会显示到屏幕上的颜色数据。</p>
<p>帧缓存包含了 3 个具体的缓存：</p>
<h4 id="1-颜色缓存"><a href="#1-颜色缓存" class="headerlink" title="1.颜色缓存"></a>1.颜色缓存</h4><p>存储每个像素点的具体颜色值的缓存，常见的具体格式可以分为：</p>
<ul>
<li>16位：RGB565，红色5位，绿色6位，蓝色5位，不保存透明通道（之所以绿色多1位是因为人眼对绿色更加敏感）；</li>
<li>24位：RGB888，红色8位，绿色8位，蓝色8位，不保存透明通道；</li>
<li>32位：RGBA8888，红色8位，绿色8位，蓝色8位，透明通道8位；</li>
</ul>
<h4 id="2-Z-缓存（深度缓存）"><a href="#2-Z-缓存（深度缓存）" class="headerlink" title="2.Z-缓存（深度缓存）"></a>2.Z-缓存（深度缓存）</h4><p>存储每个像素点的深度，用来决定是丢弃当前像素颜色还是保留，假设，新渲染的颜色在旧颜色的前面，那么就覆盖旧颜色，如果新颜色在旧颜色的后面（被遮挡了）则保留旧颜色。</p>
<h4 id="3-模板缓存"><a href="#3-模板缓存" class="headerlink" title="3.模板缓存"></a>3.模板缓存</h4><p>用来控制颜色缓存某个位置的写入操作，常用来处理阴影。</p>
<h2 id="canvas"><a href="#canvas" class="headerlink" title="canvas"></a>canvas</h2><p>一般情况下，在canvas标签实现绘图的步骤如下：1、获取canvas元素；2、向该元素请求二维图形的“绘图上下文”；3、在绘图上下文上调用相应的绘图函数，以绘制二维图形。</p>
<p>canvas本质上是提供一种上下文的机制来进行绘图的，利用canvas.getContext获取上下文，之后再用上下文支持的方法绘图。</p>
<h3 id="着色器-1"><a href="#着色器-1" class="headerlink" title="着色器"></a>着色器</h3><p>在代码中，着色器程序是以字符串的形式嵌入在JS文件中的，在程序真正开始运行前就设置好了。WebGL中着色器分两种，顶点着色器与片元着色器。顶点着色器指定了点的位置与尺寸，片元着色器指定了点的颜色；顶点着色器逐顶点操作，片元着色器逐片元操作，一旦顶点着色器执行完之后，片元着色器就会开始执行。</p>
<h3 id="坐标系统"><a href="#坐标系统" class="headerlink" title="坐标系统"></a>坐标系统</h3><p>WEBGL使用三维坐标系统，即笛卡尔坐标系，又称右手坐标系。而WEBGL的坐标系与canvas绘图区的坐标系不同，需要将前者映射到后者。</p>
<h3 id="数据传输"><a href="#数据传输" class="headerlink" title="数据传输"></a>数据传输</h3><p>物体绘制的关键在于：WebGL如何在JS程序与着色器程序之间传输数据。有两种</p>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/10/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%BB%91%E5%8A%A8%E5%9B%BE%E7%89%87%E9%AA%8C%E8%AF%81%E7%A0%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/09/10/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%BB%91%E5%8A%A8%E5%9B%BE%E7%89%87%E9%AA%8C%E8%AF%81%E7%A0%81/" class="post-title-link" itemprop="url">滑动图片验证码</a>
        </h2>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-10 21:28:16" itemprop="dateCreated datePublished" datetime="2021-09-10T21:28:16+08:00">2021-09-10</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:31:35" itemprop="dateModified" datetime="2021-11-03T16:31:35+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/" itemprop="url" rel="index"><span itemprop="name">学校项目应用</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>这个需求好像是之前项目上跟短信验证码一起写的代码，这里突然想起来，准备将这个需求的实现总结分析一下，在后续再遇到类似需求时，有一个合适的参考对象。这个需求主要在于拼图验证码在前端这里会比较复杂并且深入。相比文字拼写，12306的图片验证码都没有拼图验证码对前端的要求来的复杂。</p>
<h2 id="一、弹窗和弹窗组件"><a href="#一、弹窗和弹窗组件" class="headerlink" title="一、弹窗和弹窗组件"></a>一、弹窗和弹窗组件</h2><p>抱歉，这里我偷懒了直接用了elementUI的el-popover组件，所以小伙伴不懂的直接看elementUI官网的说明。</p>
<h2 id="二、编写基础结构"><a href="#二、编写基础结构" class="headerlink" title="二、编写基础结构"></a>二、编写基础结构</h2><p>这块属于html的基础内容，也就标题党了</p>
<h2 id="三、canvas绘制图片"><a href="#三、canvas绘制图片" class="headerlink" title="三、canvas绘制图片"></a>三、canvas绘制图片</h2><h3 id="1、canvas绘制外部img图片"><a href="#1、canvas绘制外部img图片" class="headerlink" title="1、canvas绘制外部img图片"></a>1、canvas绘制外部img图片</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mainDom = <span class="built_in">document</span>.querySelector(<span class="string">"#codeImg"</span>);</span><br><span class="line"><span class="keyword">let</span> bg = mainDom.getContext(<span class="string">"2d"</span>);</span><br><span class="line"><span class="keyword">let</span> width = mainDom.width;</span><br><span class="line"><span class="keyword">let</span> height = mainDom.height;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> blockDom = <span class="built_in">document</span>.querySelector(<span class="string">"#sliderBlock"</span>);</span><br><span class="line"><span class="keyword">let</span> block = blockDom.getContext(<span class="string">"2d"</span>);</span><br><span class="line"><span class="comment">//重新赋值，让canvas进行重新绘制</span></span><br><span class="line">blockDom.height = height;</span><br><span class="line">mainDom.height = height;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> imgsrc = <span class="built_in">require</span>(<span class="string">"../assets/images/back.jpg"</span>);</span><br><span class="line"><span class="keyword">let</span> img = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span><br><span class="line">img.style.objectFit = <span class="string">"scale-down"</span>;</span><br><span class="line">img.src = imgsrc;</span><br><span class="line">img.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  bg.drawImage(img, <span class="number">0</span>, <span class="number">0</span>, width, height);</span><br><span class="line">  block.drawImage(img, <span class="number">0</span>, <span class="number">0</span>, width, height);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这里我绘制了两个canvas，因为一个是背景一个是滑块</p>
<p>核心在于</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mainDom = <span class="built_in">document</span>.querySelector(<span class="string">"#codeImg"</span>);</span><br><span class="line"><span class="keyword">let</span> imgsrc = <span class="built_in">require</span>(<span class="string">"../assets/images/back.jpg"</span>);</span><br><span class="line"><span class="keyword">let</span> bg = mainDom.getContext(<span class="string">"2d"</span>);</span><br><span class="line"><span class="keyword">let</span> img = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span><br><span class="line">img.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    bg.drawImage(img, <span class="number">0</span>, <span class="number">0</span>, width, height);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="2、canvas绘制滑块部分"><a href="#2、canvas绘制滑块部分" class="headerlink" title="2、canvas绘制滑块部分"></a>2、canvas绘制滑块部分</h3><p><img src="/../../image/%E6%BB%91%E5%8A%A8%E5%9B%BE%E7%89%87%E9%AA%8C%E8%AF%81%E7%A0%81/8349f66d075642e2836e1fc9dfc10991tplv-k3u1fbpfcp-watermark.awebp" alt="img"></p>
<p>代码部分：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">drawBlock(ctx, xy = &#123; <span class="attr">x</span>: <span class="number">254</span>, <span class="attr">y</span>: <span class="number">109</span>, <span class="attr">r</span>: <span class="number">9</span> &#125;, type) &#123;</span><br><span class="line">  <span class="keyword">let</span> x = xy.x,</span><br><span class="line">    y = xy.y,</span><br><span class="line">    r = xy.r,</span><br><span class="line">    w = <span class="number">40</span>;</span><br><span class="line">  <span class="keyword">let</span> PI = <span class="built_in">Math</span>.PI;</span><br><span class="line">  <span class="comment">//绘制</span></span><br><span class="line">  ctx.beginPath();</span><br><span class="line">  <span class="comment">//left</span></span><br><span class="line">  ctx.moveTo(x, y);</span><br><span class="line">  <span class="comment">//top</span></span><br><span class="line">  ctx.arc(x + (w + <span class="number">5</span>) / <span class="number">2</span>, y, r, -PI, <span class="number">0</span>, <span class="literal">true</span>);</span><br><span class="line">  ctx.lineTo(x + w + <span class="number">5</span>, y);</span><br><span class="line">  <span class="comment">//right</span></span><br><span class="line">  ctx.arc(x + w + <span class="number">5</span>, y + w / <span class="number">2</span>, r, <span class="number">1.5</span> * PI, <span class="number">0.5</span> * PI, <span class="literal">false</span>);</span><br><span class="line">  ctx.lineTo(x + w + <span class="number">5</span>, y + w);</span><br><span class="line">  <span class="comment">//bottom</span></span><br><span class="line">  ctx.arc(x + (w + <span class="number">5</span>) / <span class="number">2</span>, y + w, r, <span class="number">0</span>, PI, <span class="literal">false</span>);</span><br><span class="line">  ctx.lineTo(x, y + w);</span><br><span class="line">  ctx.arc(x, y + w / <span class="number">2</span>, r, <span class="number">0.5</span> * PI, <span class="number">1.5</span> * PI, <span class="literal">true</span>);</span><br><span class="line">  ctx.lineTo(x, y);</span><br><span class="line">  <span class="comment">//修饰，没有会看不出效果</span></span><br><span class="line">  ctx.lineWidth = <span class="number">1</span>;</span><br><span class="line">  ctx.fillStyle = <span class="string">"rgba(255, 255, 255, 0.5)"</span>;</span><br><span class="line">  ctx.strokeStyle = <span class="string">"rgba(255, 255, 255, 0.5)"</span>;</span><br><span class="line">  ctx.stroke();</span><br><span class="line">  ctx[type]();</span><br><span class="line">  ctx.globalCompositeOperation = <span class="string">"xor"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>解释下：</p>
<p>参数是传入canvas对象</p>
<p>x，y轴数据</p>
<p>剪切还是填充的canvas函数（fill，clip）</p>
<p>绘制难点：（很重要，不然你没法理解它怎么绘制的）</p>
<p>绘制主要是需要理解这里的绘制是根据你设置一个起始点坐标，然后你绘制第二次的时候线就会连接到第二个点，依次连接最后回到原点就形成一个完整的图形。</p>
<p><img src="/../../image/%E6%BB%91%E5%8A%A8%E5%9B%BE%E7%89%87%E9%AA%8C%E8%AF%81%E7%A0%81/af4c4e3b4c6e429d8f1bbfa33b410badtplv-k3u1fbpfcp-watermark.awebp" alt="img"></p>
<p>用的是arc参数，主要是看这个图</p>
<p>fill是用于填充绘制的部分，clip是裁剪出绘制的部分，利用这个就可以出现一个扣掉的图片和一个裁剪出来的图片。</p>
<p>完成之后就是我的那个函数了。大家可以直接拿去用。</p>
<h3 id="3、让元素跟随鼠标点击之后滑动"><a href="#3、让元素跟随鼠标点击之后滑动" class="headerlink" title="3、让元素跟随鼠标点击之后滑动"></a>3、让元素跟随鼠标点击之后滑动</h3><p>这里其实原理非常简单，就是有一个注意点。</p>
<p>原理：</p>
<p>鼠标点击之后记录当前坐标，然后随着（mousemove）滚动的时候修改元素的left和top值就行了。</p>
<p>还有一点就是鼠标快速滑动会导致丢失滑动效果，这里需要用document，不能是元素级别的监听。</p>
<p>元素上面我只需要鉴定按下mousedown</p>
<p>代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//鼠标按下</span></span><br><span class="line">drag(e) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"鼠标按下"</span>, e);</span><br><span class="line">  <span class="keyword">let</span> dom = e.target; <span class="comment">//dom元素</span></span><br><span class="line">  <span class="keyword">let</span> slider = <span class="built_in">document</span>.querySelector(<span class="string">"#sliderBlock"</span>); <span class="comment">//滑块dom</span></span><br><span class="line">  <span class="keyword">const</span> downCoordinate = &#123; <span class="attr">x</span>: e.x, <span class="attr">y</span>: e.y &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//正确的滑块数据</span></span><br><span class="line">  <span class="keyword">let</span> checkx = <span class="built_in">Number</span>(<span class="keyword">this</span>.slider.mx) - <span class="built_in">Number</span>(<span class="keyword">this</span>.slider.bx);</span><br><span class="line">  <span class="comment">//x轴数据</span></span><br><span class="line">  <span class="keyword">let</span> x = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">const</span> move = <span class="function"><span class="params">moveEV</span> =&gt;</span> &#123;</span><br><span class="line">    x = moveEV.x - downCoordinate.x;</span><br><span class="line">    <span class="comment">//y = moveEV.y - downCoordinate.y;</span></span><br><span class="line">    <span class="keyword">if</span> (x &gt;= <span class="number">251</span> || x &lt;= <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    dom.style.left = x + <span class="string">"px"</span>;</span><br><span class="line">    <span class="comment">//dom.style.top = y + "px";</span></span><br><span class="line">    slider.style.left = x + <span class="string">"px"</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> up = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">document</span>.removeEventListener(<span class="string">"mousemove"</span>, move);</span><br><span class="line">    <span class="built_in">document</span>.removeEventListener(<span class="string">"mouseup"</span>, up);</span><br><span class="line">    dom.style.left = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(x, checkx);</span><br><span class="line">    <span class="keyword">let</span> max = checkx - <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">let</span> min = checkx - <span class="number">10</span>;</span><br><span class="line">    <span class="comment">//允许正负误差1</span></span><br><span class="line">    <span class="keyword">if</span> ((max &gt;= x &amp;&amp; x &gt;= min) || x === checkx) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">"滑动解锁成功"</span>);</span><br><span class="line">      <span class="keyword">this</span>.puzzle = <span class="literal">true</span>;</span><br><span class="line">      <span class="keyword">this</span>.tips = <span class="string">"验证成功"</span>;</span><br><span class="line">      setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.visible = <span class="literal">false</span>;</span><br><span class="line">      &#125;, <span class="number">500</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">"拼图位置不正确"</span>);</span><br><span class="line">      <span class="keyword">this</span>.tips = <span class="string">"验证失败，请重试"</span>;</span><br><span class="line">      <span class="keyword">this</span>.puzzle = <span class="literal">false</span>;</span><br><span class="line">      <span class="keyword">this</span>.canvasInit();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">document</span>.addEventListener(<span class="string">"mousemove"</span>, move);</span><br><span class="line">  <span class="built_in">document</span>.addEventListener(<span class="string">"mouseup"</span>, up);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="四、完整的页面代码"><a href="#四、完整的页面代码" class="headerlink" title="四、完整的页面代码"></a>四、完整的页面代码</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"login"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">el-form</span> <span class="attr">class</span>=<span class="string">"loginFrom"</span> <span class="attr">:model</span>=<span class="string">"logindata"</span> <span class="attr">:rules</span>=<span class="string">"rules"</span> <span class="attr">ref</span>=<span class="string">"ruleForm"</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">el-form-item</span> <span class="attr">class</span>=<span class="string">"login-item"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">h1</span> <span class="attr">class</span>=<span class="string">"login-title"</span>&gt;</span>海天酱油登录中心<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">el-form-item</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">el-form-item</span> <span class="attr">prop</span>=<span class="string">"userName"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">el-input</span></span></span><br><span class="line"><span class="tag">          <span class="attr">class</span>=<span class="string">"login-inputorbuttom"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">prefix-icon</span>=<span class="string">"el-icon-user"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">placeholder</span>=<span class="string">"登录名"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">v-model</span>=<span class="string">"logindata.userName"</span></span></span><br><span class="line"><span class="tag">        &gt;</span><span class="tag">&lt;/<span class="name">el-input</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">el-form-item</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">el-form-item</span> <span class="attr">prop</span>=<span class="string">"password"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">el-input</span></span></span><br><span class="line"><span class="tag">          <span class="attr">class</span>=<span class="string">"login-inputorbuttom"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">prefix-icon</span>=<span class="string">"el-icon-lock"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">placeholder</span>=<span class="string">"密码"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">v-model</span>=<span class="string">"logindata.password"</span></span></span><br><span class="line"><span class="tag">        &gt;</span><span class="tag">&lt;/<span class="name">el-input</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">el-form-item</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--&lt;el-form-item prop="verificationCode"&gt;</span></span><br><span class="line"><span class="comment">        &lt;el-input</span></span><br><span class="line"><span class="comment">          class="login-inputorbuttom"</span></span><br><span class="line"><span class="comment">          v-model="logindata.verificationCode"</span></span><br><span class="line"><span class="comment">        &gt;&lt;/el-input&gt;</span></span><br><span class="line"><span class="comment">      &lt;/el-form-item&gt;--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">el-form-item</span> <span class="attr">class</span>=<span class="string">"login-item"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">el-button</span></span></span><br><span class="line"><span class="tag">          <span class="attr">class</span>=<span class="string">"login-inputorbuttom login-bottom"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">type</span>=<span class="string">"primary"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">v-popover:popover</span></span></span><br><span class="line"><span class="tag">          @<span class="attr">click</span>=<span class="string">"visible = !visible"</span></span></span><br><span class="line"><span class="tag">          &gt;</span>登 录<span class="tag">&lt;/<span class="name">el-button</span></span></span><br><span class="line"><span class="tag">        &gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">el-form-item</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">el-form</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--验证码弹窗--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">el-popover</span></span></span><br><span class="line"><span class="tag">      <span class="attr">popper-class</span>=<span class="string">"slidingPictures"</span></span></span><br><span class="line"><span class="tag">      <span class="attr">ref</span>=<span class="string">"popover"</span></span></span><br><span class="line"><span class="tag">      <span class="attr">trigger</span>=<span class="string">"manual"</span></span></span><br><span class="line"><span class="tag">      <span class="attr">v-model</span>=<span class="string">"visible"</span></span></span><br><span class="line"><span class="tag">    &gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"sliding-pictures"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"vimg"</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">"sliderBlock"</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">"codeImg"</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"slider"</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"track"</span> <span class="attr">:class</span>=<span class="string">"&#123; pintuTrue: puzzle &#125;"</span>&gt;</span></span><br><span class="line">            &#123;&#123; tips &#125;&#125;</span><br><span class="line">          <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"button el-icon-s-grid"</span> @<span class="attr">mousedown.prevent</span>=<span class="string">"drag"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"operation"</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">span</span></span></span><br><span class="line"><span class="tag">            <span class="attr">title</span>=<span class="string">"关闭验证码"</span></span></span><br><span class="line"><span class="tag">            @<span class="attr">click</span>=<span class="string">"visible = false"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">class</span>=<span class="string">"el-icon-circle-close"</span></span></span><br><span class="line"><span class="tag">          &gt;</span><span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">span</span></span></span><br><span class="line"><span class="tag">            <span class="attr">title</span>=<span class="string">"刷新验证码"</span></span></span><br><span class="line"><span class="tag">            @<span class="attr">click</span>=<span class="string">"canvasInit"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">class</span>=<span class="string">"el-icon-refresh-left"</span></span></span><br><span class="line"><span class="tag">          &gt;</span><span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">el-popover</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="actionscript">  name: <span class="string">"login"</span>,</span></span><br><span class="line">  data() &#123;</span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      tips: <span class="string">"拖动左边滑块完成上方拼图"</span>,</span></span><br><span class="line">      logindata: &#123;</span><br><span class="line"><span class="actionscript">        userName: <span class="string">""</span>,</span></span><br><span class="line"><span class="actionscript">        password: <span class="string">""</span>,</span></span><br><span class="line"><span class="actionscript">        verificationCode: <span class="string">""</span></span></span><br><span class="line">      &#125;,</span><br><span class="line">      rules: &#123;&#125;,</span><br><span class="line"><span class="actionscript">      visible: <span class="literal">false</span>,</span></span><br><span class="line"><span class="actionscript">      <span class="comment">//滑块x轴数据</span></span></span><br><span class="line">      slider: &#123;</span><br><span class="line">        mx: 0,</span><br><span class="line">        bx: 0</span><br><span class="line">      &#125;,</span><br><span class="line"><span class="actionscript">      <span class="comment">//拼图是否正确</span></span></span><br><span class="line"><span class="actionscript">      puzzle: <span class="literal">false</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  watch: &#123;</span><br><span class="line">    visible(e) &#123;</span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (e === <span class="literal">true</span>) &#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.canvasInit();</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">this</span>.puzzle = <span class="literal">false</span>;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  beforeCreate() &#123;&#125;,</span><br><span class="line">  created() &#123;&#125;,</span><br><span class="line">  beforeMount() &#123;&#125;,</span><br><span class="line">  mounted() &#123;&#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line"><span class="actionscript">    <span class="comment">//拼图验证码初始化</span></span></span><br><span class="line">    canvasInit() &#123;</span><br><span class="line"><span class="actionscript">      <span class="comment">//生成指定区间的随机数</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> random = <span class="function">(<span class="params">min, max</span>) =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * (max - min + <span class="number">1</span>) + min);</span></span><br><span class="line">      &#125;;</span><br><span class="line"><span class="actionscript">      <span class="comment">//x: 254, y: 109</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> mx = random(<span class="number">127</span>, <span class="number">244</span>),</span></span><br><span class="line">        bx = random(10, 128),</span><br><span class="line">        y = random(10, 99);</span><br><span class="line"></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.slider = &#123; mx, bx &#125;;</span></span><br><span class="line"></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.draw(mx, bx, y);</span></span><br><span class="line">    &#125;,</span><br><span class="line"><span class="actionscript">    <span class="comment">//鼠标按下</span></span></span><br><span class="line">    drag(e) &#123;</span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(<span class="string">"鼠标按下"</span>, e);</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> dom = e.target; <span class="comment">//dom元素</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> slider = <span class="built_in">document</span>.querySelector(<span class="string">"#sliderBlock"</span>); <span class="comment">//滑块dom</span></span></span><br><span class="line"><span class="actionscript">      <span class="keyword">const</span> downCoordinate = &#123; x: e.x, y: e.y &#125;;</span></span><br><span class="line"></span><br><span class="line"><span class="actionscript">      <span class="comment">//正确的滑块数据</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> checkx = <span class="built_in">Number</span>(<span class="keyword">this</span>.slider.mx) - <span class="built_in">Number</span>(<span class="keyword">this</span>.slider.bx);</span></span><br><span class="line"><span class="actionscript">      <span class="comment">//x轴数据</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> x = <span class="number">0</span>;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> move = <span class="function"><span class="params">moveEV</span> =&gt;</span> &#123;</span></span><br><span class="line">        x = moveEV.x - downCoordinate.x;</span><br><span class="line"><span class="actionscript">        <span class="comment">//y = moveEV.y - downCoordinate.y;</span></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (x &gt;= <span class="number">251</span> || x &lt;= <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span></span><br><span class="line"><span class="actionscript">        dom.style.left = x + <span class="string">"px"</span>;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">//dom.style.top = y + "px";</span></span></span><br><span class="line"><span class="actionscript">        slider.style.left = x + <span class="string">"px"</span>;</span></span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> up = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="built_in">document</span>.removeEventListener(<span class="string">"mousemove"</span>, move);</span></span><br><span class="line"><span class="javascript">        <span class="built_in">document</span>.removeEventListener(<span class="string">"mouseup"</span>, up);</span></span><br><span class="line"><span class="actionscript">        dom.style.left = <span class="string">""</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(x, checkx);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> max = checkx - <span class="number">5</span>;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> min = checkx - <span class="number">10</span>;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">//允许正负误差1</span></span></span><br><span class="line">        if ((max &gt;= x &amp;&amp; x &gt;= min) || x === checkx) &#123;</span><br><span class="line"><span class="javascript">          <span class="built_in">console</span>.log(<span class="string">"滑动解锁成功"</span>);</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.puzzle = <span class="literal">true</span>;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.tips = <span class="string">"验证成功"</span>;</span></span><br><span class="line"><span class="javascript">          setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">this</span>.visible = <span class="literal">false</span>;</span></span><br><span class="line">          &#125;, 500);</span><br><span class="line"><span class="actionscript">        &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">          <span class="built_in">console</span>.log(<span class="string">"拼图位置不正确"</span>);</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.tips = <span class="string">"验证失败，请重试"</span>;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.puzzle = <span class="literal">false</span>;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">this</span>.canvasInit();</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="built_in">document</span>.addEventListener(<span class="string">"mousemove"</span>, move);</span></span><br><span class="line"><span class="javascript">      <span class="built_in">document</span>.addEventListener(<span class="string">"mouseup"</span>, up);</span></span><br><span class="line">    &#125;,</span><br><span class="line">    draw(mx = 200, bx = 20, y = 50) &#123;</span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> mainDom = <span class="built_in">document</span>.querySelector(<span class="string">"#codeImg"</span>);</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> bg = mainDom.getContext(<span class="string">"2d"</span>);</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> width = mainDom.width;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> height = mainDom.height;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> blockDom = <span class="built_in">document</span>.querySelector(<span class="string">"#sliderBlock"</span>);</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> block = blockDom.getContext(<span class="string">"2d"</span>);</span></span><br><span class="line"><span class="actionscript">      <span class="comment">//重新赋值，让canvas进行重新绘制</span></span></span><br><span class="line">      blockDom.height = height;</span><br><span class="line">      mainDom.height = height;</span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> imgsrc = <span class="built_in">require</span>(<span class="string">"../assets/images/back.jpg"</span>);</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> img = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span></span><br><span class="line"><span class="actionscript">      img.style.objectFit = <span class="string">"scale-down"</span>;</span></span><br><span class="line">      img.src = imgsrc;</span><br><span class="line"><span class="actionscript">      img.onload = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line">        bg.drawImage(img, 0, 0, width, height);</span><br><span class="line">        block.drawImage(img, 0, 0, width, height);</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> mainxy = &#123; <span class="attr">x</span>: mx, <span class="attr">y</span>: y, <span class="attr">r</span>: <span class="number">9</span> &#125;;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> blockxy = &#123; <span class="attr">x</span>: bx, <span class="attr">y</span>: y, <span class="attr">r</span>: <span class="number">9</span> &#125;;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.drawBlock(bg, mainxy, <span class="string">"fill"</span>);</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.drawBlock(block, blockxy, <span class="string">"clip"</span>);</span></span><br><span class="line">    &#125;,</span><br><span class="line"><span class="actionscript">    <span class="comment">//绘制拼图</span></span></span><br><span class="line">    drawBlock(ctx, xy = &#123; x: 254, y: 109, r: 9 &#125;, type) &#123;</span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> x = xy.x,</span></span><br><span class="line">        y = xy.y,</span><br><span class="line">        r = xy.r,</span><br><span class="line">        w = 40;</span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> PI = <span class="built_in">Math</span>.PI;</span></span><br><span class="line"><span class="actionscript">      <span class="comment">//绘制</span></span></span><br><span class="line">      ctx.beginPath();</span><br><span class="line"><span class="actionscript">      <span class="comment">//left</span></span></span><br><span class="line">      ctx.moveTo(x, y);</span><br><span class="line"><span class="actionscript">      <span class="comment">//top</span></span></span><br><span class="line"><span class="actionscript">      ctx.arc(x + (w + <span class="number">5</span>) / <span class="number">2</span>, y, r, -PI, <span class="number">0</span>, <span class="literal">true</span>);</span></span><br><span class="line">      ctx.lineTo(x + w + 5, y);</span><br><span class="line"><span class="actionscript">      <span class="comment">//right</span></span></span><br><span class="line"><span class="actionscript">      ctx.arc(x + w + <span class="number">5</span>, y + w / <span class="number">2</span>, r, <span class="number">1.5</span> * PI, <span class="number">0.5</span> * PI, <span class="literal">false</span>);</span></span><br><span class="line">      ctx.lineTo(x + w + 5, y + w);</span><br><span class="line"><span class="actionscript">      <span class="comment">//bottom</span></span></span><br><span class="line"><span class="actionscript">      ctx.arc(x + (w + <span class="number">5</span>) / <span class="number">2</span>, y + w, r, <span class="number">0</span>, PI, <span class="literal">false</span>);</span></span><br><span class="line">      ctx.lineTo(x, y + w);</span><br><span class="line"><span class="actionscript">      ctx.arc(x, y + w / <span class="number">2</span>, r, <span class="number">0.5</span> * PI, <span class="number">1.5</span> * PI, <span class="literal">true</span>);</span></span><br><span class="line">      ctx.lineTo(x, y);</span><br><span class="line"><span class="actionscript">      <span class="comment">//修饰，没有会看不出效果</span></span></span><br><span class="line">      ctx.lineWidth = 1;</span><br><span class="line"><span class="actionscript">      ctx.fillStyle = <span class="string">"rgba(255, 255, 255, 0.5)"</span>;</span></span><br><span class="line"><span class="actionscript">      ctx.strokeStyle = <span class="string">"rgba(255, 255, 255, 0.5)"</span>;</span></span><br><span class="line">      ctx.stroke();</span><br><span class="line">      ctx[type]();</span><br><span class="line"><span class="actionscript">      ctx.globalCompositeOperation = <span class="string">"xor"</span>;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="css"><span class="selector-class">.slidingPictures</span> &#123;</span></span><br><span class="line">  padding: 0;</span><br><span class="line">  width: 300px;</span><br><span class="line">  border-radius: 2px;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">scoped</span> <span class="attr">lang</span>=<span class="string">"scss"</span>&gt;</span></span><br><span class="line"><span class="css"><span class="selector-id">#login</span> &#123;</span></span><br><span class="line">  display: flex;</span><br><span class="line">  flex-flow: row;</span><br><span class="line">  justify-content: flex-end;</span><br><span class="line">  align-items: center;</span><br><span class="line">  width: 100%;</span><br><span class="line">  height: 100%;</span><br><span class="line">  background-image: url("../assets/images/back.jpg");</span><br><span class="line">  background-size: 100% 100%;</span><br><span class="line"><span class="css">  <span class="selector-class">.loginFrom</span> &#123;</span></span><br><span class="line">    width: 300px;</span><br><span class="line">    margin-top: -10vw;</span><br><span class="line">    margin-right: 10vw;</span><br><span class="line"><span class="css">    <span class="selector-class">.login-item</span> &#123;</span></span><br><span class="line">      display: flex;</span><br><span class="line">      justify-content: center;</span><br><span class="line">      align-items: center;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.login-title</span> &#123;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">color</span>: <span class="selector-id">#ffffff</span>;</span></span><br><span class="line">      font-size: 16px;</span><br><span class="line">      margin-bottom: 10px;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.login-bottom</span> &#123;</span></span><br><span class="line">      margin-top: 15px;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.login-bottom</span><span class="selector-pseudo">:hover</span> &#123;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-tag">rgba</span>(28, 136, 188, 0<span class="selector-class">.5</span>);</span></span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.login-bottom</span><span class="selector-pseudo">:active</span> &#123;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-tag">rgba</span>(228, 199, 200, 0<span class="selector-class">.5</span>);</span></span><br><span class="line">    &#125;</span><br><span class="line">    /deep/.login-inputorbuttom &#123;</span><br><span class="line">      height: 40px;</span><br><span class="line">      width: 300px;</span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-tag">rgba</span>(57, 108, 158, 0<span class="selector-class">.5</span>);</span></span><br><span class="line">      border-radius: 20px;</span><br><span class="line"><span class="css">      <span class="selector-tag">border</span>: <span class="selector-id">#396c9e</span> 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span>;</span></span><br><span class="line">      font-size: 14px;</span><br><span class="line"><span class="css">      <span class="selector-tag">color</span>: <span class="selector-id">#ffffff</span>;</span></span><br><span class="line"><span class="css">      <span class="selector-class">.el-input--small</span>,</span></span><br><span class="line"><span class="css">      <span class="selector-class">.el-input__inner</span> &#123;</span></span><br><span class="line">        line-height: 43px;</span><br><span class="line">        border: none;</span><br><span class="line"><span class="css">        <span class="selector-tag">color</span>: <span class="selector-id">#ffffff</span>;</span></span><br><span class="line">        font-size: 14px;</span><br><span class="line">        height: 40px;</span><br><span class="line">        border-radius: 20px;</span><br><span class="line">        background: transparent;</span><br><span class="line">        text-align: center;</span><br><span class="line">      &#125;</span><br><span class="line"><span class="css">      <span class="selector-class">.el-input__icon</span> &#123;</span></span><br><span class="line">        line-height: 40px;</span><br><span class="line">        font-size: 16px;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="css"><span class="comment">/*该样式最终是以弹窗插入*/</span></span></span><br><span class="line"><span class="css"><span class="selector-class">.sliding-pictures</span> &#123;</span></span><br><span class="line">  width: 100%;</span><br><span class="line"><span class="css">  <span class="selector-class">.vimg</span> &#123;</span></span><br><span class="line">    width: 100%;</span><br><span class="line">    height: 170px;</span><br><span class="line"><span class="css">    <span class="selector-id">#codeImg</span>,</span></span><br><span class="line"><span class="css">    <span class="selector-id">#sliderBlock</span> &#123;</span></span><br><span class="line">      padding: 7px 7px 0 7px;</span><br><span class="line">      width: inherit;</span><br><span class="line">      height: inherit;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-id">#codeImg</span> &#123;</span></span><br><span class="line">      //display: none;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-id">#sliderBlock</span> &#123;</span></span><br><span class="line">      position: absolute;</span><br><span class="line">      z-index: 4000;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="css">  <span class="selector-class">.slider</span> &#123;</span></span><br><span class="line">    width: 100%;</span><br><span class="line">    height: 65px;</span><br><span class="line"><span class="css">    <span class="selector-tag">border-bottom</span>: <span class="selector-id">#c7c9d0</span> 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span>;</span></span><br><span class="line">    display: flex;</span><br><span class="line">    align-items: center;</span><br><span class="line">    justify-content: flex-start;</span><br><span class="line"><span class="css">    <span class="selector-class">.track</span> &#123;</span></span><br><span class="line">      margin-left: 7px;</span><br><span class="line">      width: 286px;</span><br><span class="line">      height: 38px;</span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-tag">rgba</span>(28, 136, 188, 0<span class="selector-class">.5</span>);</span></span><br><span class="line">      border-radius: 25px;</span><br><span class="line">      font-size: 14px;</span><br><span class="line">      line-height: 38px;</span><br><span class="line">      padding-right: 15px;</span><br><span class="line">      padding-left: 70px;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.pintuTrue</span> &#123;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-id">#67c23a</span>;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">color</span>: <span class="selector-id">#ffffff</span>;</span></span><br><span class="line">    &#125;</span><br><span class="line"><span class="css">    <span class="selector-class">.button</span> &#123;</span></span><br><span class="line">      position: absolute;</span><br><span class="line">      width: 50px;</span><br><span class="line">      height: 50px;</span><br><span class="line">      line-height: 48px;</span><br><span class="line"><span class="css">      <span class="selector-tag">background</span>: <span class="selector-id">#ffffff</span>;</span></span><br><span class="line"><span class="css">      <span class="selector-tag">box-shadow</span>: <span class="selector-id">#b9bdc8</span> 0 0 3<span class="selector-tag">px</span>;</span></span><br><span class="line">      border-radius: 50%;</span><br><span class="line">      left: 7px;</span><br><span class="line">      text-align: center;</span><br><span class="line">      font-size: 28px;</span><br><span class="line"><span class="css">      <span class="selector-tag">color</span>: <span class="selector-id">#3e5d8b</span>;</span></span><br><span class="line"><span class="css">      &amp;<span class="selector-pseudo">:hover</span> &#123;</span></span><br><span class="line"><span class="css">        <span class="selector-tag">color</span>: <span class="selector-id">#2181bd</span>;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="css">  <span class="selector-class">.operation</span> &#123;</span></span><br><span class="line">    width: 100%;</span><br><span class="line">    height: 40px;</span><br><span class="line">    &gt; span &#123;</span><br><span class="line"><span class="css">      <span class="selector-tag">color</span>: <span class="selector-id">#9fa3ac</span>;</span></span><br><span class="line">      display: inline-block;</span><br><span class="line">      width: 40px;</span><br><span class="line">      font-size: 25px;</span><br><span class="line">      line-height: 40px;</span><br><span class="line">      text-align: center;</span><br><span class="line"><span class="css">      &amp;<span class="selector-pseudo">:hover</span> &#123;</span></span><br><span class="line"><span class="css">        <span class="selector-tag">background</span>: <span class="selector-id">#e2e8f5</span>;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    
    
    <div>
      
    </div>
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/3/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/3/">3</a><span class="page-number current">4</span><a class="page-number" href="/page/5/">5</a><span class="space">&hellip;</span><a class="page-number" href="/page/10/">10</a><a class="extend next" rel="next" href="/page/5/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

